Google News
logo
Scala - Interview Questions
Explain the concept of lazy evaluation in Scala.
Lazy evaluation is a feature in Scala that delays the evaluation of an expression until its result is actually needed. It allows you to defer the computation of a value until it is explicitly accessed, potentially saving unnecessary computation for unused or expensive operations.

In Scala, lazy evaluation is achieved through the use of the `lazy` keyword, which can be applied to both `val` and `def` declarations. When a value or method is declared as lazy, its initialization or execution is postponed until the first access, and the result is cached for subsequent accesses.

Here's an example to illustrate the concept of lazy evaluation :
lazy val expensiveComputation: Int = {
  println("Performing expensive computation...")
  // Expensive computation logic here
  42
}

println("Before accessing the lazy value")
println(expensiveComputation) // Evaluation happens here
println("After accessing the lazy value")
println(expensiveComputation) // Evaluation is skipped, cached result is used​
In this example, the `expensiveComputation` value is declared as lazy. When the program runs, the line `println("Before accessing the lazy value")` is executed, but the actual computation of `expensiveComputation` is not triggered yet. It is only evaluated when it is accessed for the first time, which happens on the line `println(expensiveComputation)`. At this point, the output "Performing expensive computation..." is printed, indicating that the computation is being performed. The computed result (42) is then cached for subsequent accesses, as seen when `expensiveComputation` is accessed again.

Lazy evaluation is particularly useful when dealing with computations that are resource-intensive or have side effects. By deferring the computation until it is needed, you can avoid unnecessary work and optimize the performance of your code.
Advertisement