Skip to content

What is "by Lazy" in kotlin

Devrath edited this page Feb 28, 2024 · 4 revisions

In Kotlin, by lazy is a way to implement a property in a way that its value is computed only upon the first access, and subsequent accesses return the cached result. It is particularly useful for initializing properties where the computation is expensive and you want to delay it until it's actually needed.

Here's a basic example of how by lazy works: Code

class Example {
    val expensiveProperty: String by lazy {
        println("Computing the value...")
        "This is the result"
    }
}


fun main(args: Array<String>) {


    val example = Example()

    // The value is not computed yet
    println("<-------- Before accessing the property ------->")

    // Accessing the property for the first time triggers the computation
    println(example.expensiveProperty)

    // The value is now cached, accessing the property again does not recompute it
    println("<-------- After accessing the property again ------->")

    // Observe here the computation is not triggered but instead the cached result is returned
    println(example.expensiveProperty)
}

Output

<-------- Before accessing the property ------->
Computing the value...
This is the result
<-------- After accessing the property again ------->
This is the result

In this example, the expensiveProperty is only computed when it is first accessed. The lambda expression provided to lazy is the initializer for the property, and its result is cached and returned for subsequent accesses.

This can be useful for scenarios where you want to avoid unnecessary computations, especially if the property might not be used during the entire lifecycle of the object.

Thread safety modes

public enum class LazyThreadSafetyMode {

    /**
     * Locks are used to ensure that only a single thread can initialize the [Lazy] instance.
     */
    SYNCHRONIZED,

    /**
     * Initializer function can be called several times on concurrent access to uninitialized [Lazy] instance value,
     * but only the first returned value will be used as the value of [Lazy] instance.
     */
    PUBLICATION,

    /**
     * No locks are used to synchronize access to the [Lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined.
     *
     * This mode should not be used unless the [Lazy] instance is guaranteed never to be initialized from more than one thread.
     */
    NONE,
}
Clone this wiki locally