Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between lazy{} vs getter() initialization in kotlin

In kotlin we can use both of these approach lazy{} and getter()

lazy initializaiton:

internal val connector by lazy {
        serviceConnector
    }

getter():

internal val connector : ServiceConnector
        get() = serviceConnector

When to use which approach and what actually does these two approach under the hood. Which one is best approach?

like image 670
0xAliHn Avatar asked Mar 17 '19 19:03

0xAliHn


People also ask

What is lazy initialization in Kotlin?

lazy initialisation is a delegation of object creation when the first time that object will be called. The reference will be created but the object will not be created. The object will only be created when the first time that object will be accessed and every next time the same reference will be used.

What is the difference between lazy and Lateinit in Kotlin?

In the above code, you can see that the object of the HeavyClass is created only when it is accessed and also the same object is there all over the main() function. Lazy is mainly used when you want to access some read-only property because the same object is accessed throughout.

Which is thread-safe late init or lazy?

The Lazy initialization is thread-safe. Lateinit can only be used with var . Lazy initialization is used with the val property.

Is lazy thread-safe in Kotlin?

It is lazy and thread-safe, it initializes upon first call, much as Java's static initializers. You can declare an object at top level or inside a class or another object.


1 Answers

When you use the lazy delegate, the val is initialized only when you use it the first time. So, in your code, the first time you access connector, the code inside the lambda is run, and the result is assigned to the val.

get(), instead, is used to redefine what happens when you try to access the val.

like image 111
gpunto Avatar answered Oct 23 '22 12:10

gpunto