0Pricing
Kotlin Academy · Lesson

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

  1. by lazy: Deferred Initialization Deep Dive
  2. observable and vetoable Delegates
  3. Writing a Custom ReadWriteProperty Delegate
  4. Delegates for Preferences, Map-Backed Properties & Logging
← Back to Kotlin Academy