【发布时间】:2017-02-05 13:38:58
【问题描述】:
我有这种情况
trait D {
def someMethod(): Unit = {}
}
trait C {
val locations: Seq[Int]
someSomethingWithLocations() // calling this in constructor
def someSomethingWithLocations(): Unit = {
print(locations.length)
}
}
class B extends D with C {
override val locations: Seq[Int] = 1 :: 2 :: 3 :: Nil
someMethod()
}
def main(args: Array[String]): Unit = {
val b = new B
}
当我运行此代码时,someSomethingWithLocations 抛出空指针异常,因为尚未调用 B 类的构造函数,因此未初始化位置。
如果我将 B 类的声明更改为
class B extends{
override val locations: Seq[Int] = 1 :: 2 :: 3 :: Nil
someMethod()
} with D with C
编译器抱怨找不到 someMethod()。我该如何解决这个问题?
现在我已将位置声明移至不同的特征,我的程序按预期工作,但我想尽可能避免不必要的特征。
【问题讨论】: