3

这可能已被 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) 没有正确初始化而支付惰性值税。该怎么办?

4

1 回答 1

11

您可以使用早期初始化程序

class System1 extends {
  val bar = Foo("npe")
} with Mixin with Confluent {
  // ...
}

scala> new System1
res3: System1 = System1@1d0bfedd
于 2012-09-28T21:35:16.903 回答