Home
Scala
lazy Keyword Example
This page was last reviewed on Dec 19, 2023.
Dot Net Perls
Lazy. 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.
class
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.
Example. 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.
Step 1 We instantiate the Test class with the new keyword. And then we invoke the print() function.
Step 2 We print a message indicating that our method has begun executing. Then we access the lazy field.
Step 3 In the getName() function, we print a message and return a String that is the resulting value of the name field.
Step 4 We print the name field (it was accessed and initialized so that it could passed to the println method).
println
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
Lazy effect. 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.
So This means without the "lazy" keyword, the field is initialized eagerly, before our print() def is ever run.
Lazy init Start Name is 123
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 19, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.