caeus caeus - 22 days ago 5
Scala Question

Cake pattern with val members which depend on abstract members

So take this trait

trait SomeTrait{
val x:Int
val y:Int
val z=x*y
}


And then this implementation

class SomeImpl extends SomeTrait{
val x=5
val y=2
println(z) //prints 0 why?
}


Why does it print 0? and how can I avoid that! I want z to be a val, in case it is some kind of expensive computation.

Answer

z must be marked as either lazy val or def

trait SomeTrait{
  val x:Int
  val y:Int
  lazy val z=x*y
}

For a detailed explanation, refer to When to use val or def in Scala traits?

Comments