← Back to Scala Course | Chapter 12: Advanced Features | Lesson 5 of 7

Lazy val

A lazy val waits to be calculated until you first need it, like cooking dinner only when someone is hungry. After that, it remembers the answer and does not repeat the work.

In this page:

  1. Lazy val
Syntax
scala
lazy val name: Type = expensive_expression    // evaluated on first access only

Lazy val

A lazy val delays its initializer's evaluation until the value is first accessed, rather than immediately when it's declared, and the computed result is cached for all later accesses.

This is useful for expensive computations that might not always be needed, or for breaking initialization-order problems between values. Unlike a plain val, accessing a lazy val for the first time has a small overhead to check and set its initialized state.

Note: A lazy val's initializer runs exactly once, the first time it's accessed -- every later access just returns the cached result.

Example: Lazy val

markup
object Main extends App {
  lazy val expensive: Int = {
    println("Computing expensive value...")
    42
  }

  println("Before accessing expensive")
  println(expensive)
  println(expensive) // no recomputation, uses cached value
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting a lazy val to run at definition, when its code runs at the first access only.
  2. Using a lazy val whose initializer has side effects and being surprised by when they happen.
  3. Using lazy val in a hot path and forgetting the cost of thread-safe initialization.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.