[Scala] “Lazy” val in Scala
What is the keyword “lazy” in Scala, and how is it being used? Any pitfall we can get from it? Let’s explore.
What is “lazy” val?
When declared in front of val
, the compiler will not immediately evaluate the expression, but it will evaluate the bound expression at its first access. In a subsequent access, it will just return the result without any further execution or calculation.
def fib(n: Int): Int {
// fib() is a method that calculates a fib number
}object ValStore {
lazy val fortyFive = fib(45)
lazy val fortiySix = fib(46)
}
Pitfalls of “lazy”
During an evaluation of a lazy val, the whole instance is locked, which means when different lazy vals are accessed from multiple threads, the calculation on them will need to happen sequentially.
In the above case, there are two lazy vals in ValStore singleton. If we try to access them from different threads, the one needs to wait until the first execution is done.
In the below example, when the first initialization (4) executes a calculation on the lazy val fortyFive (1), another initialization (5) cannot execute a calculation on another lazy val fortySix (2) because the whole instance ValStore is locked until the first initialization is done
object ValStore {
lazy val fortyFive = fib(45) // (1)
lazy val fortySix = fib(46) // (2)
}object Scenario1 {
def run = {
val result = Future.sequence(Seq( // (3)
Future {
println("starting (45)")
ValStore.fortyFive // (4)
println("done (45)")
},
Future {
println("starting (46)")
ValStore.fortySix // (5)
println("done (46)")
}
))
Await.result(result, 1.minute)
}
}
Conclusion
I explored some basics of lazy in Scala. More examples will come as I acquire deeper knowledge on this!