这可能已被 Jesse Eichar 的博客文章所涵盖——我仍然无法弄清楚如何在不使用惰性val 的情况下更正以下问题,以便修复 NPE:
给定
trait FooLike { def foo: String }
case class Foo(foo: String) extends FooLike
trait Sys {
type D <: FooLike
def bar: D
}
trait Confluent extends Sys {
type D = Foo
}
trait Mixin extends Sys {
val global = bar.foo
}
第一次尝试:
class System1 extends Mixin with Confluent {
val bar = Foo("npe")
}
new System1 // boom!!
第二次尝试,改变mixin顺序
class System2 extends Confluent with Mixin {
val bar = Foo("npe")
}
new System2 // boom!!
现在我同时使用了这两种方法bar
并且global
非常频繁,因此我不想仅仅因为 Scala (2.9.2) 没有正确初始化而支付惰性值税。该怎么办?