🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Lazy Values

A lazy value is a value that is not built until it is used for the first time. It is built once and then reused on every later use.

A lazy value builds on first use only

The marker prints when the value is first used, not when it is defined. The second use prints no marker.

@main def main(): Unit =
  lazy val big = { println("built"); 42 }
  println("before")
  println(big)
  println(big)

An eager val builds at once and a lazy val waits

The eager marker prints before start, while the lazy marker waits. The lazy marker prints only when the lazy value is used.

@main def main(): Unit =
  val eager = { println("eager built"); 1 }
  lazy val slow = { println("lazy built"); 2 }
  println("start")
  println(eager)
  println(slow)

An unused lazy value is never built

The lazy value is defined but never used. Only done prints, with no building marker.

@main def main(): Unit =
  lazy val unused = { println("never built"); 99 }
  println("done")

Example

@main def main(): Unit =
  lazy val total = { println("adding"); 10 + 20 }
  println(total)
  println(total + 1)
  println(total)

Key points

  • Lazy val: a value whose building work is delayed until its first use.
  • First use: the moment that triggers the building work exactly once.
  • Later use: a reuse of the stored result with no rebuilding work.
  • Unused lazy val: a lazy value that is never used and never built.
  • Eager val: a plain val that is built at once when its line runs.

In this example, total is lazy, so adding prints only on its first use. The first use gives 30, the next use adds 1 to the stored 30 to give 31, and the last use gives 30 again with no second marker.

Note

laziness delays work, it does not repeat work. A lazy value is built at most once.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

Given lazy val x = { println("made"); 5 }, then println("hi"), then println(x) twice, how many times does made print?