O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required