Scala:误用特征,给出运行时错误

Scala: Mis-using traits, gives runtime error

抱歉话题太笼统了;我只是不太确定我做错了什么。

我有一个class结构

trait BaseType {
  val property: String
}

trait MiddleTrait extends BaseType {
  val myProperty = property.length.toString
  def userProperty() = {
    myProperty
  }
}

object Top extends MiddleTrait {
  val property = "value given here"
}  

哪个编译;但遇到 运行 时间错误 - java.lang.RuntimeException: java.lang.NoClassDefFoundError: Could not initialize class controllers.test.Top$

将 MiddleTrait 更新为 def myProperty = property.length.toString 它将 运行 正常。

我希望更好地理解这背后的理论,这样我就可以预测错误,而不会先看到它在 运行 时间失败

谢谢

当我将您的代码粘贴到 Scala 2.11.6 REPL 中时,一开始我没有收到任何错误。尝试访问 myProperty 将导致 NullPointerException

scala> Top.myProperty
java.lang.NullPointerException
  at MiddleTrait$class.$init$(<console>:12)
  ... 35 elided

抛出 NullPointerException 是因为 MiddleTraitTop 之前初始化,此时 property 仍然是 null (see spec on template evaluation)。如果将 myProperty 转换为函数,错误就会消失,因为该函数是在完全初始化的 Top.

上调用的

当我在 NullPointerException

之后再次尝试访问 myProperty 时,你引用的错误出现了
scala> Top.myProperty
java.lang.NoClassDefFoundError: Could not initialize class Top$
  ... 33 elided