0
0
KotlinConceptBeginner · 3 min read

What is Lazy Property in Kotlin: Explanation and Example

In Kotlin, a lazy property is a special kind of property that delays its initialization until it is first accessed. This means the value is computed only once when needed, saving resources if the property is never used.
⚙️

How It Works

Imagine you have a box that you don't want to open until you really need what's inside. A lazy property works like that box. It holds the instructions to create a value but waits to run those instructions until you ask for the value for the first time.

When you access a lazy property, Kotlin runs the code to create the value, stores it, and then returns it. Any later access just returns the stored value without running the code again. This saves time and memory if the property is never used or if creating it is expensive.

💻

Example

This example shows a lazy property that prints a message when it is initialized and returns a string. The message appears only once, the first time the property is accessed.
kotlin
class Example {
    val lazyValue: String by lazy {
        println("Computing the lazy value...")
        "Hello, Lazy!"
    }
}

fun main() {
    val example = Example()
    println("Before accessing lazyValue")
    println(example.lazyValue)
    println(example.lazyValue)
}
Output
Before accessing lazyValue Computing the lazy value... Hello, Lazy! Hello, Lazy!
🎯

When to Use

Use lazy properties when creating a value is costly or time-consuming, and you want to delay this work until it is actually needed. For example, loading a large file, connecting to a database, or performing a complex calculation.

This helps improve performance and resource use, especially if the property might never be accessed during the program run.

Key Points

  • Lazy initialization means the value is created only when first accessed.
  • The value is cached after creation, so it is not recomputed.
  • It is useful for expensive or optional properties.
  • Kotlin provides by lazy syntax to declare lazy properties easily.

Key Takeaways

A lazy property delays its initialization until first use, saving resources.
The value is computed once and then cached for future accesses.
Use lazy properties for expensive or optional computations.
Kotlin's 'by lazy' syntax makes lazy properties simple to declare.