Greedy Coder
Greedy Coder

Reputation: 1326

Lazy evaluations with var

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.

Questions

Scala version I am using : Scala 2.12.0

lazy val error

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

Answers (1)

Tzach Zohar
Tzach Zohar

Reputation: 37822

First, some terminology:

  • The keyword val is used to define a "value definition" - a definition that is evaluated once.
  • The keyword var defines a variable, which can be changed after it is first assigned a value.
  • So when the compiler says "lazy modifier allowed only with value definitions", it means just that - that only 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

Related Questions