1

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.

caeus
  • 3,084
  • 1
  • 22
  • 36

1 Answers1

3

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?

Community
  • 1
  • 1
Andrey
  • 8,882
  • 10
  • 58
  • 82