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?
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.
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.
The Lazy initialization is thread-safe. Lateinit can only be used with var . Lazy initialization is used with the val property.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With