Lazy val
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: