Câu hỏi phỏng vấn Kotlin
Câu hỏi

Explain lazy initialization in Kotlin

Câu trả lời

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:

Defining a Lazy Property

To define a lazy property, you use the by lazy delegate and provide a lambda expression that initializes the property:

kotlin Copy
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.

Accessing a Lazy Property

When you access a lazy property for the first time, the lambda expression is executed, and the result is stored for subsequent accesses:

kotlin Copy
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.

Thread-Safety

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

middle

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between suspending vs. blocking?

middle

Why would you use apply in Kotlin?

senior

Provide a real use case when inline classes may be useful

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào