Sobes.tech
Junior — Middle

Is it possible to determine whether a value has been assigned to a variable declared with the lateinit modifier?

sobes.tech AI

Answer from AI

In Kotlin, a variable declared with the lateinit modifier is initialized later, not at the point of declaration. To check whether it has been initialized, you can use reflection with the property ::variableName.isInitialized.

Example:

lateinit var myVar: String

fun checkInitialization() {
    if (::myVar.isInitialized) {
        println("myVar is initialized: $myVar")
 } else {
        println("myVar is not initialized")
}

This allows avoiding UninitializedPropertyAccessException when trying to access an uninitialized lateinit variable.

Is it possible to determine whether a value has been… - sobes.tech