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

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
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
y
res1: java.lang.String = Vigilance

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.