Kotlin Lazy Initialization: Smart Memory in 2025!
For efficient memory management, Kotlin brings lazy initialization—a slick way to save resources!
With the lazy keyword, objects spring to life only when called—otherwise, they stay dormant. The lazy() function takes a lambda and returns a Lazy instance, acting as a delegate for lazy properties. It’s all about dodging unnecessary object creation! ⏳
Lazy Rules:
- ๐ซ Only for non-nullable variables—no ? allowed.
- ๐ Must use val—var isn’t an option.
- ✅ Initialized once, then cached for reuse.
- ⏰ Stays uninitialized until first access.
class Demo {
val myName: String by lazy {
println("Welcome to Lazy declaration")
"Kotlin Lazy" // Returned value
}
}
fun main() {
val obj = Demo()
println("First call: " + obj.myName) // Triggers init
println("Second call: " + obj.myName) // Cached, no re-init
} // Outputs: "Welcome to Lazy declaration", "First call: Kotlin Lazy", "Second call: Kotlin Lazy" ๐
Lazy Benefits:
- ⚡ Saves memory by delaying creation.
- ๐ Reuses the cached result after first use.
- ๐ Ideal for heavy objects or late-needed data.
Lazy vs Lateinit ๐ค
Lazy and lateinit both delay initialization, but they’re different beasts:
fun main() {
// Lazy example
val lazyValue: String by lazy { "Lazy Init" }
println(lazyValue) // Triggers init, outputs: Lazy Init
// Lateinit example
lateinit var lateValue: String
lateValue = "Late Init"
println(lateValue) // Outputs: Late Init
}
Choosing Wisely:
- ⏳ Lazy: Use for immutable (val), auto-initialized values.
- ๐ง Lateinit: Use for mutable (var), manually set values.
- ๐ Lazy caches; lateinit can change.
- ⚡ Lazy is safer (no crash risk); lateinit needs care.
Thread Safety with Lazy ๐งต
Lazy is thread-safe by default—perfect for multi-threaded apps:
fun main() {
val heavyObject: String by lazy {
println("Initializing in thread: ${Thread.currentThread().name}")
"Heavy Data"
}
// Simulate multiple threads
Thread { println(heavyObject) }.start()
Thread { println(heavyObject) }.start()
println(heavyObject)
} // Only one "Initializing" message, all get "Heavy Data" ๐งต
Thread Safety Perks:
- ๐งต Synchronized by default—first thread wins, others wait.
- ๐ Single initialization, shared across threads.
- ⚡ Optional modes (e.g., LazyThreadSafetyMode.PUBLICATION) for flexibility.
- ✅ No race conditions—safe and sound!
..
Comments
Post a Comment