One of the most interesting features of the Kotlin syntax is Lazy initialization but it is also a concept that can be a little tricky to understand. The concept of Lazy initialization was designed to prevent the unnecessary initialization of objects. Lets imagine that you have a are running a program and you want to print out a string. That’s pretty easy to do right?
If we run this it looks very similar but as we dig further something very interesting begins to happen. In order to illustrate this we will print the name multiple times and also add another print statement withing the lazy block.
Once we run this code we can see that “processing” was printed once while the name was printed multiple times. Why is this? Well, the reason is that when the first println(name) function was called, Kotlin evaluated, executed the code in the Lazy block and saved the computed value. This computed value was then returned each subsequent time without having to evaluate and execute the code in the lazy block again.
As you can see, “processing…” was printed to the console and a few seconds later “Paul” was printed out three times almost simultaneously. This is because when the first println(name) function was called, the lazy block was evaluated and executed, the computed value was then saved by Kotlin and when the second and third println(name) function was called the computed value of the name variable only needed to be returned. With Lazy initialization, the value gets computed ONLY upon first access.