Laziness Explained
Compute values only when needed.
What Is Laziness?
In Scala, most values are strict: they are computed the moment you define them. Laziness flips this. A lazy value is only computed when it is first needed, never before.
This matters when computations are expensive, may fail, or might never be used at all. Why pay for work nobody asks for?
Strict val
A normal val evaluates its right-hand side immediately, even if you never read it again.
Run this and notice that "computing" prints before "after". The work happens at definition time.
object Demo extends App {
val x = { println("computing"); 42 }
println("after")
println(x)
}All lessons in this course
- Laziness Explained
- Building a LazyList
- Infinite Streams
- Taking and Filtering Lazily