例如我有这个代码:
abstract class A {
def functionA() {
val a : A = null; // take null just for temporary, because I cannot think what should to put here
a.functionB
}
def functionB() {
print("hello")
}
}
class C extends A{
}
object Main extends App {
val c : C = new C()
c.functionB // print hello
c.functionA // ERROR
}
在functionA
,我想声明一个对象以防万一:如果当前类是 C,a 将具有 C 类型。如果当前类是 D,a 将具有 D 类型。因为我不能这样做:
val a : A = new A // because A is abstract
在 Java 中,我可以轻松地做到这一点,但在 Scala 中我不能这样做。请帮帮我。
谢谢 :)