Scala difference between val, lazy val and def

We have seen val and def in previous SKBs but we haven’t encountered the keyword lazy before.

Try to figure out by yourself what lazy does. Make sure to read the print statements in the console as you run the code.

Did you figure it out ?

The keyword lazy allows a value to not be evaluated until the very first time it is called. If you call the value again, the previously computed value will be used.

With val the value is computed instantly as the value is declared. You were able to see the print statement early in the log, before all the others.

And for def, this is a method, so each time you call the method, you are recomputing the result.

Summary:

  • val: Computed once when declared
  • lazy val: Computed once when called
  • def: Computed each time it is called

Reveal more information and clues
Load Exercise