Avoiding NPE in trait initialization without using lazy vals

Posted by 0__ on Stack Overflow See other posts from Stack Overflow or by 0__
Published on 2012-09-28T21:00:43Z Indexed on 2012/09/28 21:37 UTC
Read the original article Hit count: 316

Filed under:
|

This is probably covered by the blog entry by Jesse Eichar—still I can't figure out how to correct the following without residing to lazy vals so that the NPE is fixed:

Given

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
}

First attempt:

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

new System1  // boom!!

Second attempt, changing mixin order

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

new System2  // boom!!

Now I use both bar and global very heavily, and therefore I don't want to pay a lazy-val tax just because Scala (2.9.2) doesn't get the initialisation right. What to do?

© Stack Overflow or respective owner

Related posts about scala

Related posts about nullpointerexception