Junior — Middle
How to determine if a variable with the lateinit modifier has been initialized in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, to check whether a variable with the lateinit modifier has been initialized, the isInitialized property of the variable's reflection is used. This works only for class properties declared with lateinit var.
Example:
class Example {
lateinit var text: String
fun isTextInitialized(): Boolean {
return this::text.isInitialized
}
}
fun main() {
val example = Example()
println(example.isTextInitialized()) // false
example.text = "Hello"
println(example.isTextInitialized()) // true
}
Thus, you can safely check if a variable has been initialized before using it to avoid an UninitializedPropertyAccessException.