One handy feature of Scala is lazy val
, where the evaluation of a val
is delayed until it's necessary (at first access).
Ofcourse a lazy val
must have some overhead - somewhere Scala must keep track of whether the value has already been evaluated and the evaluation must be synchronized, because multiple threads might try to access the value for the first time at the same time.
What exactly is the cost of a lazy val
- is there a hidden boolean flag associated with a lazy val
to keep track if it has been evaluated or not, what exactly is synchronized and are there any more costs?
And a follow-up question: Suppose I do this:
class Something {
lazy val (x, y) = { ... }
}
Is this the same as having two separate lazy val
s x
and y
or do I get the overhead only once, for the pair (x, y)
?