Lazy val – calling by need
Enough wandering in the Java wonderland! Coming back to Scala, we have vals and lazy vals. If some object creation is expensive, we can stick the lazy keyword before val to initialize it on its first use.
Open the REPL and try out the following:
scala> lazy val p = { | println ("Initializing") | 9 | } p: Int = <lazy> scala> println(p) Initializing // p accessed for the first time 9 scala> println(p) // cached result of p 9
We stick the lazy
keyword before the val
keyword. We are using a block expression to initialize p
. In Scala, a block is a sequence of expressions enclosed in {
}. The last expression in the block is the
value of the block. The value of the block here is 9
. On the other hand, the value of an assignment expression is Unit. The Unit type is equivalent to the void
type in Java.