Scala difference between val, lazy val and def

We have seenvalanddefin previous SKBs but we haven't encountered the keywordlazybefore.

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

Did you figure it out ?

The keywordlazyallows 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.

Withvalthe 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 fordef, 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