A lazy val is an immutable Scala binding that postpones its right-hand side until first reference, then caches the result. This matters when a by-name argument may be referenced repeatedly: ordinary by-name evaluation can repeat work or effects, while a local lazy val evaluates once and reuses the value. section 5.1
Cache a repeated by-name argument
In maybeTwice, referencing i twice evaluates a by-name argument twice. Introducing lazy val j = i changes the body to use j + j: the argument is forced once, its result is cached, and both references reuse it. section 5.1
The same pattern supports lazy data structures. A smart cons constructor stores lazy head and tail values, preserving deferred computation while ensuring each thunk does its work only once when forced. section 5.2.1
def cons[A](hd: => A, tl: => LazyList[A]): LazyList[A] = lazy val head = hd lazy val tail = tl Cons(() => head, () => tail)
Inspect how lazy vals memoize both components of a LazyList constructor before exposing them through deferred functions. section 5.2.1
