[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!

--

--

--

Software Engineer | Scala | Functional Programming

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Programming and designing

Announcement of NFT Event 2nd week winner [EN/KR]

Pick a card, any card: implementing the Monzo Plus card selection animation on Android

Manufacturing Execution Systems: 8 top Solutions

How to get a fully automated API lifecycle with Azure API Management

9 Test Automation Predictions for 2021

Docker for Ubuntu

How to manage your Kafka consumers from the producer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
mj park

mj park

Software Engineer | Scala | Functional Programming

More from Medium

Scala: for-comprehension contexts do not mix

[Scala] Implicit Parameters

Polymorphism and its types in Scala

Essential effects