by lazy: Deferred Initialization Deep Dive
Explore lazy initialization modes: SYNCHRONIZED, PUBLICATION, and NONE.
What Is by lazy?
by lazy defers initialization of a val until first access. The lambda runs once and caches the result.
val greeting: String by lazy {
println("Computing...")
"Hello, Kotlin!"
}
fun main() {
println(greeting) // prints Computing... then Hello, Kotlin!
println(greeting) // prints Hello, Kotlin! (cached)
}Lazy Syntax
The by lazy delegate takes a lambda returning the value type inferred from the property declaration.
val pi: Double by lazy { Math.PI }
val appName: String by lazy { "MyApp v1.0" }
fun main() {
println(pi) // 3.141592653589793
println(appName) // MyApp v1.0
}All lessons in this course
- by lazy: Deferred Initialization Deep Dive
- observable and vetoable Delegates
- Writing a Custom ReadWriteProperty Delegate
- Delegates for Preferences, Map-Backed Properties & Logging