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

Lazy val

In this page:

  1. Lazy val

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
}
🔒

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.