Skip to content

What is "by Lazy" in kotlin

Devrath edited this page Feb 25, 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.

Clone this wiki locally