Home »
Scala
Scala lazy val
Scala | lazy val: In this tutorial, we are going to learn about the Scala lazy val. We will also see some important concepts about lazy val with examples.
Submitted by Shivang Yadav, on April 08, 2020
Scala | lazy val
Scala programming language allows the user to initialize a variable as a lazy val. A lazy variable is used when we need to save memory overheads while object creation. Using the lazy keyword, you can halt the initialization of the variable until the time it is first used or accessed in the code.
Program to illustrate lazy val
object myObject
{
def main(args:Array[String])
{
lazy val newBlock = {
println ("This will be printed only in case of first initialization.")
"Hello!"
}
println("The block is not initialized yet!")
println("First Call : ")
println(newBlock)
println("Second Call : ")
println(newBlock)
}
}
Output
The block is not initialized yet!
First Call :
This will be printed only in case of first initialization.
Hello!
Second Call :
Hello!
As in the code, the block is initialized after the first print statement when it is called. The print statement of the newBlock will be printed only once. In the second call, it will return the string "Hello!" and does not print anything.