特徵的構造我有這種情況Call類構造器之前在斯卡拉
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()未找到。我該如何解決這個問題?
現在我已經將位置聲明移到了不同的特徵上,我的程序按預期工作,但如果可能的話,我想避免不必要的特徵。