Explain lazy initialization in Kotlin
Explain lazy initialization in Kotlin
Lazy initialization in Kotlin is a way to delay the initialization of a property until it is first accessed. This can be useful for properties that are expensive to create or may not be needed in all cases. Here's how it works:
To define a lazy property, you use the by lazy
delegate and provide a lambda expression that initializes the property:
val lazyProperty: String by lazy {
println("Initializing lazyProperty")
"Hello, Kotlin!"
}
In this example, lazyProperty
is a String
that will be initialized when it is first accessed.
When you access a lazy property for the first time, the lambda expression is executed, and the result is stored for subsequent accesses:
println(lazyProperty)
// Output: Initializing lazyProperty
// Hello, Kotlin!
On the first access, you'll see the message "Initializing lazyProperty" printed, indicating that the property is being initialized. Subsequent accesses will not trigger the initialization again.
By default, lazy initialization in Kotlin is thread-safe. If multiple threads try to access the lazy property simultaneously, the initialization will only happen once, and all threads will get the same instance.
If you need ...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào