2012-09-28 23 views
3

这可能是覆盖的blog entry由Jesse Eichar,我仍然无法弄清楚如何更正以下而不诉诸懒瓦尔斯从而使NPE是固定的:避免在特质初始化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!! 

第二次尝试,改变混入或明镜

class System2 extends Confluent with Mixin { 
    val bar = Foo("npe") 
} 

new System2 // boom!! 

现在我同时使用barglobal非常沉重,因此,我不想支付懒-VAL税只是因为Scala(2.9.2)没有得到正确的初始化。该怎么办?

+0

其实,这是有可能在我的具体情况下,加上'bar'作为构造参数:'类系统3(VAL条:美孚)延伸汇合与密新;新的System3(Foo(“:-)”))' - 但是如果我没有构造函数arg的可能性,我仍然对如何解决这个问题感兴趣。 –

回答

11

您可以使用early initializer

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

scala> new System1 
res3: System1 = [email protected] 
+3

哇,在斯卡拉> 4年后我不敢相信我还在遇到新事物! –