What is lazy evaluation in Scala?
Answer
Lazy evaluation in Scala defers computation until the value is actually needed. lazy val: evaluated once on first access: lazy val expensiveResult = computeExpensively(). The computation runs the first time expensiveResult is accessed, and the result is cached for subsequent accesses. Streams (LazyList in Scala 2.13+): lazily evaluated infinite sequences: val naturals = LazyList.from(1) — only elements that are actually requested are computed. Call-by-name parameters: def and(a: Boolean, b: => Boolean) — the b argument is evaluated only if needed. This enables short-circuit evaluation in custom functions. Lazy evaluation avoids unnecessary computation, enables working with infinite data structures, and can improve performance for rarely-used expensive values. The downside is less predictable evaluation timing, which can complicate debugging.
Previous
What is the for-comprehension in Scala?
Next
What is Scala's type system and what is type inference?