🐦 Kotlin
Intermediate
What is by lazy in Kotlin?
Answer
by lazy is a property delegate that defers initialization of a property until it is first accessed, then caches the result for all subsequent accesses. The lambda you pass is executed only once: val database: Database by lazy { Database.initialize() }. By default, lazy is thread-safe (SYNCHRONIZED mode — uses a lock). For single-threaded code, you can use lazy(LazyThreadSafetyMode.NONE) for better performance. This pattern is especially useful for expensive initializations that might not be needed in all code paths, like database connections or view references.