Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am an Android application developer based out of Seattle. I specialize in building Full Stack Mobile applications with NodeJS and Firebase back-ends.
  • Location
    Seattle, WA
  • Work
    Android Developer at AppLabs, Inc
  • Joined

More fromPaul Franco

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp