DEV Community

Cover image for Kotlin - "Lazy" initialization
Paul Franco
Paul Franco

Posted on

Kotlin - "Lazy" initialization

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?
1-SYjvlFCUlNVrK7tctOMQWA

But what if getting this string was from an expensive operation? Well this is where we can use Lazy initialization.1-4pCZ2RVPLTENyCcJmj9eZA

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.
1-WnS0CweLt-bAhdab5rxNkA

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.

Now, let imagine that we are performing some sort of network call or long running operation. To simulate this we will add a sleep function in our code.
Screen Shot 2020-09-18 at 5.02.41 AM
Screen Shot 2020-09-18 at 5.02.56 AM

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.

Top comments (0)