You are totally correct in your example the console will be printed only once. This is because it is going to be evaluated at the same time that the val fLazy is created.

But the difference between val and lazy val is that in the second case it is only evaluated at the time we use it, whereas in the first case it is evaluated at the time you create the val.

If you want to see this in action execute this code:

// Once is printed

def printOnce(f: => Int): Unit = {

val fLazy = f

}

println(printOnce({println("Once"); 1}))

In this example the function will be evaluated only once at the time you create the val. However, in the second example (see below) the function will never be evaluated, because the val is never used:

// Once is never printed

def printOnce(f: => Int): Unit = {

lazy val fLazy = f

}

println(printOnce({println("Once"); 1}))

The key difference between lazy val and val is all to do with when they are evaluated! I hope this comment helps you and thank you for reading my article!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store