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

When to use lateinit over lazy initialization in Kotlin?

Câu trả lời

Here is an explanation of when to use lateinit vs lazy initialization in Kotlin:

lateinit

Use lateinit when:

  • The property needs to be initialized before it is used. lateinit allows you to declare a non-null property without initializing it immediately.
  • The property is a var (mutable) and will be assigned a value before it is accessed. If you try to access a lateinit property before it is initialized, a UninitializedPropertyAccessException will be thrown.
  • The property is a member of a class, not a local variable in a function.
  • The property is not nullable (i.e. it is not declared with a ? after the type name).

Some examples of when lateinit is useful:

  • Injecting dependencies into a class using a dependency injection framework
  • Initializing a property that requires some setup logic before it can be used
  • Assigning a value to a property from a const...
middle

middle

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

junior

What is the idiomatic way to remove duplicate strings from array?

expert

What is SAM Conversion in Kotlin?

middle

Explain lazy initialization in Kotlin

Bình luận

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

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