lazy delegates

4 0 0
                                        

lazy() - this is a standard delegate function and not a class but works the same. It returns an object of Lazy<T>. Meaning the class Lazy<T> will serve as a delegate to your properties. The Lazy<T> is your representative to manage your get and set of your property value.

Why Lazy? It because it is not an immediate assigning of values. It will only be access when it is called. The first time it is called, it will store the result. Subsequent calls will just pass in the remembered result.

syntax:

val propertyName: Type by lazy{

     //this is the lambda function statement

}

lazy() function requires one parameter which is a lambda function. Normally, the parameter is enclosed in a parenthesis but with a lambda function, you can put the function inside body which the compiler can infer as a parameter of that function. It allows getValue() method only and not setValue(). So, don't use var when declaring a variable.

===================

fun main(){

    val laz = PracticeLazy("Pass the message")

    println(laz.message)

}

class PracticeLazy(private val message: String, private val name:){

    val message: String by lazy{

        LazyThreadSafetyMode.PUBLICATION

        LazyThreadSafetyMode.NONE

        doSomethingForLazy()

    }

    private fun doSomethingForLazy(): String{

        return "$name: $message"

    }

}

==================

Result:

dummy: Pass the message


Note: 

1. lazy properties is synchronized. Meaning if one thread does the get the value for lazy, all the other threads will have the same value as well. And this is the default.

2. LazyThreadSafetyMode.PUBLICATION - if you don't want it to be synchronized.

3. LazyThreadSafetyMode.NONE - if you are sure that the lazy will run on the same thread.

4. If I did not include the PUBLICATION and NONE in the lazy() function parameter, the runtime is slow because of synchronization.

Kotlin ProgrammingМесто, где живут истории. Откройте их для себя