0
0
Kotlinprogramming~5 mins

Lazy property delegation in Kotlin

Choose your learning style9 modes available
Introduction

Lazy property delegation helps you create a value only when you need it, saving time and resources.

When a property value is expensive to create and you want to delay its creation until it's actually needed.
When you want to avoid unnecessary calculations or loading data until the property is accessed.
When you want to improve app startup time by delaying some work.
When you want to cache a value after the first calculation so it doesn't run again.
When you want simple, clean code to handle delayed initialization.
Syntax
Kotlin
val propertyName: Type by lazy {
    // code to create the value
}

The lazy block runs only once, the first time you access the property.

After that, the same value is returned every time without running the block again.

Examples
This example prints a message only once when greeting is first accessed, then returns the string.
Kotlin
val greeting: String by lazy {
    println("Computing greeting...")
    "Hello, Kotlin!"
}
A simple lazy property that returns 42 when accessed for the first time.
Kotlin
val number: Int by lazy { 42 }
Sample Program

This program shows that the lazy block runs only once, even if the property is accessed multiple times.

Kotlin
fun main() {
    val lazyValue: String by lazy {
        println("Calculating lazyValue...")
        "I am lazy"
    }

    println("Before accessing lazyValue")
    println(lazyValue)
    println(lazyValue)
}
OutputSuccess
Important Notes

Lazy properties are thread-safe by default, so they work well in multi-threaded apps.

If you want a different thread-safety mode, you can pass a parameter to lazy().

Summary

Lazy property delegation delays creating a value until it is needed.

The value is created once and reused on later accesses.

This helps save resources and keeps code clean.