Reputation: 1326
I know about lazy val
and that code is evaluated only when it is called, but I am not able to understand certain things with lazy and var.
Scala version I am using : Scala 2.12.0
It says lazy is allowed only with value definitions. I am a bit confused here, isnt everything a value in scala? and var is just a keyword right and what it has to do with the type.
Upvotes: 2
Views: 673
Reputation: 37822
First, some terminology:
val
is used to define a "value definition" - a definition that is evaluated once. var
defines a variable, which can be changed after it is first assigned a value.val
and not var
can follow the lazy
keyword. Why does Scala not support lazy var
?
I'm guessing that marking a var
as lazy would not be well defined: what would be evaluated lazily - the first assignment only? Each and every assignment? And would a re-assignment count as a trigger for the previous assignment or not? There might also be some implementation issues (e.g. how do we make sure a variable isn't assigned while a previous value is being calculated?).
Upvotes: 5