In Scala 3.3 sometimes it is beneficial to delay initialization of a field until it is first used. This can even speed up a program, by avoiding unneeded initializations.
When we assign a field in a class
, it is initialized before any other logic is run. But when we specify "lazy" upon the field, it is initialized as late as possible.
Usually in Scala programs, we do not have classes named "Test," but this program is for demonstration purposes. We have a lazy field "name" upon the Test class
.
class
with the new keyword. And then we invoke the print()
function.getName()
function, we print a message and return a String
that is the resulting value of the name field.println
method).class Test { lazy val name = getName(); def getName(): String = { // Step 3: this function is called when name is accessed. println("Lazy init") return "Name is " + 123.toString() } def print() = { // Step 2: print a message, and then initialize the lazy field. println("Start") // Step 4: print the lazily-initialized value. println(name) } } object Program { def main(args: Array[String]) = { // Step 1: create an instance of the Test class and call print. val test = new Test() test.print() } }Start Lazy init Name is 123
Consider what happens if we remove the lazy keyword in the program. The program still compiles and runs, but the terms "Lazy init
" are printed before the "Start" message.
print()
def
is ever run.Lazy init Start Name is 123
By delaying initializations, sometimes we find that they are not needed. A field may never be needed in a certain execution of the program.
In this way, lazy can improve performance by reducing unneeded work. And "lazy" can help with time-sensitive initializations that involve the current time or an IO operation that must be recent.