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

Explain the difference betwee...

Câu trả lời

Certainly! I'd be happy to explain the differences between lateinit and lazy in Kotlin in detail.

lateinit

lateinit is a keyword in Kotlin that allows you to declare a non-null variable without initializing it immediately. Instead, you can initialize it later in the code. This is useful when you know that the variable will be assigned a value before it is used, but you don't want to pass a null value or use a nullable type (String? instead of String).

Here are some key points about lateinit:

  1. It can only be used with non-null types (var, not val).
  2. The variable must be initialized before it is accessed. If you try to access it before initialization, a UninitializedPropertyAccessException will be thrown.
  3. It is commonly used for dependency injection or when a variable is initialized in a separate method or constructor.
  4. It is not available for primitive types (Int, Boolean, etc.) or for nullable types (String?).

Example:

kotlin Copy
class MyClass {
    lateinit var myVariable: String

    fun initialize() {
        myVariable = "Hello, Kotlin!"
    }

    fun printVariable() {
        println(myVariable) // No exception thrown because myVariable is initialized
    }
}

lazy

lazy is another keyword in...

expert

expert

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

middle

What is lateinit in Kotlin and when would you use it?

junior

How to initialize an array in Kotlin with values?

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