Home »
Scala
What does a Lazy val do in Scala?
By IncludeHelp Last updated : October 09, 2024
Lazy Val in Scala is used when we need to save memory overheads while object creation. It is created using a lazy keyword.
Syntax:
lazy val val_name = value
Lazy val vs val declaration
In Scala, variables declared using the val keyword are initialized when the value is defined in the code, not when it is executed even if there is no code that calls the variable. Whereas in case of lazy val declaration of variables, they are initialized at the first call to it in the code and no variable will be created if no call is made.
What does a lazy val do?
It saves memory when variables declared are not used.
Yes, lazy declaration of variables can save memory when extra values are defined in code but never used in the code. In such cases, lazy val initialization will save memory and compilation time.
Scala example for 'variable with val declaration'
object MyClass {
def main(args: Array[String]): Unit = {
val newBlock1 = {
println(
"\nThis will be printed only in case of first initialization of block1 ."
)
"Hello from block1"
}
val newBlock2 = {
println(
"\nThis will be printed only in case of first initialization of block2."
)
"Hello from block2!"
}
println("Block initialised with val declaration!!")
print("First Call : ")
println(newBlock1)
print("Second Call : ")
println(newBlock1)
}
}
Output
This will be printed only in case of first initialization of block1 .
This will be printed only in case of first initialization of block2.
Block initialised with val declaration!!
First Call : Hello from block1
Second Call : Hello from block1
Scala example for 'variable with lazy val declaration'
object MyClass {
def main(args: Array[String]): Unit = {
lazy val newBlock1 = {
println(
"\nThis will be printed only in case of first initialization of block1 ."
)
"Hello from block1"
}
lazy val newBlock2 = {
println(
"\nThis will be printed only in case of first initialization of block2."
)
"Hello from block2!"
}
println("Block initialised with lazy val declaration!!")
print("First Call : ")
println(newBlock1)
print("Second Call : ")
println(newBlock1)
}
}
Output
Block initialised with lazy val declaration!!
First Call :
This will be printed only in case of first initialization of block1 .
Hello from block1
Second Call : Hello from block1
As we can see in the above examples, in program 1, we have used the val keyword to declare the objects which are initialized when they are declared in the code. But in the code the block2 is never used by is initialized which increases computation overheads and memory. But in program 2 lazy val is used for declaring objects which are initialized when the first call to it is made, which is never done for myBlock2 in the code and not initialized in program 2.