liveBook · Manning

Lazy val

As explained in Functional Programming in Scala, Second Edition

A lazy val is an immutable Scala binding whose right-hand side is evaluated on first reference and whose result is cached for later references.

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

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains first-reference evaluation and caching, then applies the pattern to memoized lazy-list constructors.
Examples
Uses maybeTwice2 and a LazyList cons constructor to show one-time evaluation and cached head and tail values.
What it assumes
Assumes basic Scala bindings and functions while developing strictness and by-name evaluation terminology alongside the feature.
What you can do after
Apply it in Scala to prevent repeated evaluation of deferred expressions and memoize lazy data-structure components.
How it connects
Connects lazy val to by-name parameters, strictness, memoization, smart constructors, and lazy lists.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.