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

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

Câu trả lời

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

In Kotlin, lateinit is a modifier that allows you to declare a non-null variable without initializing it immediately. It is used for properties that will be initialized before they are used, but not in the constructor.

Here's how lateinit works:

  1. You declare a variable with the lateinit modifier, specifying its type.
  2. You initialize the variable later in the code, before it is used for the first time.
  3. If you try to access the variable before it is initialized, Kotlin will throw a UninitializedPropertyAccessException.

Here's an example:

kotlin Copy
class MyClass {
    lateinit var myProperty: String

    fun myFunction() {
        myProperty = "Hello, Kotlin!"
        println(myProperty)
    }
}

In this example, myProperty is declared as lateinit and is initialized in the myFunction() method before it is used.

You would typ...

middle

middle

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

middle

What is a difference between a class and object in Kotlin?

expert

What is SAM Conversion in Kotlin?

middle

How is it recommended to create constants in Kotlin?

Bình luận

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

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