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:
Syntax
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
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
}
Login to try C/C++/Java/PHP code in the editor
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
- Expecting a
lazy valto run at definition, when its code runs at the first access only. - Using a
lazy valwhose initializer has side effects and being surprised by when they happen. - Using
lazy valin 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: