Kotlin

lazy — Lazily Computed val

admin by @admin ADMIN
Jun 18, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`by lazy { ... }` runs the block on first access, caches the result. Default mode is thread-safe (synchronized). Perfect for expensive initialization where you might never need the value.
Kotlin
Raw
class UserService {
    val expensiveCache: Map<String, String> by lazy {
        println("computing cache…")                  // prints exactly ONCE
        // ...heavy computation...
        mapOf("user1" to "Alice", "user2" to "Bob")
    }
}

fun main() {
    val svc = UserService()
    println("created service")
    println(svc.expensiveCache["user1"])             // first access — block runs
    println(svc.expensiveCache["user2"])             // cached — no re-compute

    // Top-level lazy too
    val regex: Regex by lazy { Regex("[a-z]+\\d+") }
    println(regex.matches("abc123"))

    // Threading modes
    // by lazy(LazyThreadSafetyMode.NONE) { ... }    // skip sync if single-threaded
    // by lazy(LazyThreadSafetyMode.PUBLICATION) { ... } // may compute multiple times
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.