How to use lazy val in Scala and what is the difference between lazy val and val ?

DeeKay September 30, 2011 at 12:03 am · Scala

Difference between val and lazy val is that, a val is executed when it is defined whereas lazy val is executed when it is accessed for the first time.

Below example shows how to use val and lazy val –

scala> val x = { println("x"); "Howdy"}
x: java.lang.String = Howdy

scala> lazy val y = { println("y"); "Vigilance"}
y: java.lang.String = <lazy>

scala> x
res0: java.lang.String = Howdy

scala> y
res1: java.lang.String = Vigilance