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
}
Create a free account and build your private vault. Share publicly whenever you want.