Local delegates

Delegation is powerful, we've already seen that, but think of a common situation where inside a method we declare and initialize a property, then we apply a logic which will either use the property or will continue without it. For example, the following is such a program:

fun useDelegate(shouldPrint:Boolean) { 
    val localDelegate = "Delegate Used" 
    if(shouldPrint) { 
        println(localDelegate) 
    } 
     
    println("bye bye") 
} 

In this program, we will use the localDelegate property, only if the shouldPrint value is true, else we won't use it. But it would always take space in memory since it is declared and initialized. An option to avoid this memory blockage is to have the property inside the if block, but it's a simple dummy program, and here we can easily afford to move the variable declaration inside the if block, whereas in many real-life scenarios, moving the variable declaration inside the if block is not possible.

So, what's the solution? Yes, using lazy delegation can save our life here. But it wasn't possible in Kotlin before the arrival of Kotlin 1.1.

So, the following is the updated program:

fun useDelegate(shouldPrint:Boolean) { 
    val localDelegate by lazy { 
        "Delegate Used" 
    } 
    if(shouldPrint) { 
        println(localDelegate) 
    } 
     
    println("bye bye") 
} 

Though we only used lazy for this example, from Kotlin 1.1, we can have any delegation applied in local properties.

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

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