What is lateinit in Kotlin and when would you use it?
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:
lateinit
modifier, specifying its type.UninitializedPropertyAccessException
.Here's an example:
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào