The lazy function

The lateinit keyword works only on the var properties. The Delegates.notNull()  function works properly only with var properties, too.

So, what should we do when using val properties? Kotlin provides you with another delegation—lazy, that's meant for val properties only. But it works in a slightly different way.

Unlike lateinit and Delegates.notNull(), you must specify how you want to initialize the variable at the time of declaration. So, what's the benefit? The initialization will not be called until the variable is actually used. That's why this delegate is called lazy; it enables lazy initialization of properties.

The following is a code example:

val myLazyVal:String by lazy { 
    println("Just Initialised") 
    "My Lazy Val" 
} 
 
fun main(args: Array<String>) { 
    println("Not yet initialised") 
    println(myLazyVal) 
} 

So in this program, we declared a String val property—myLazyVal with a lazy delegate. We used (printed) that property in the second line of the main function.

Now, let's focus on the variable declaration. The lazy delegate accepts a lambda that's expected to return the value of the property.

So, let's have a look at the output:

Notice that the output clearly shows that the property got initialized after the first line of the main method executed, that is, when the property was actually used. This lazy initialization of properties can save your memory by a significant measure. It also comes as a handy tool in some situations, for example, think of a situation where you want to initialize the property with some other property/context, which would be available only after a certain point (but you have the property name); in that situation, you can simply keep the property as lazy, and then you can use it when it's confirmed that the initialization will be successful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.27.171