September 2018
Intermediate to advanced
398 pages
9h 43m
English
When we use the lazy prefix in front of val or var (as shown in the following code), it is evaluated only when needed:
class LazyDemo { lazy val lazyVal = { println("Evaluating lazyVal") "Hello" } } val lazyDemo = new LazyDemo //lazyDemo: LazyDemo = LazyDemo@13ca84d5
When we instantiate the class, the block at the right side of the assignment is not evaluated. It will only get evaluated when we use the variable, as shown in the following code:
lazyDemo.lazyVal + " World" //Evaluating lazyVal //res0: String = Hello World
This mechanism allows you to defer the evaluation of computationally expensive operations. For instance, you could use it to start an application quickly and run the initialization code only when the first user ...
Read now
Unlock full access