How to check if a lateinit variable is initialized in Kotlin?

September 25, 2022 No comments Kotlin lateinit isInitialized

1. Introduction

In this short article, we are going to present how to find out that lateinit variable in Kotlin has been initialized.

2. Late-initialized variable

The non-null variables usually must be initialized in the constructor and this is the normal behavior in many programming languages, Kotlin is not an exception in this case. However, that approach is not so obvious in cases when variables are initialized through the dependency injection or other configuration methods. In such situations, we cannot add variable initializer in the constructor but still want to avoid constantly checking if variables are null in the class body.

To handle such cases Kotlin introduced the lateinit modifier:

class Lateinit {

    lateinit var lateinitTest: LateinitTest

    fun setup() {
        lateinitTest = LateinitTest()
    }

    fun test() {
        lateinitTest.method()
    }
}

In this example, the lateinitTest is marked with lateinit modifier. This adds some extra features to this variable.

3. Checking if the lateinit variable is initialized

We can check whether a lateinit variable has been initialized using the .isInitialized property:

class Lateinit {

    lateinit var lateinitTest: LateinitTest

    fun setup() {
        println(this::lateinitTest.isInitialized);
        lateinitTest = LateinitTest()
    }

    fun test() {
        println(this::lateinitTest.isInitialized);
        lateinitTest.method()
    }
}

fun main() {
    val lt = Lateinit();

    lt.setup(); // false
    lt.test(); // true
}

In this example before initializing the variable: lateinitTest = LateinitTest() the println(this::lateinitTest.isInitialized) command will display false. After lateinitTest variable has been initialized .isInitialized property will be presenting true. Note that using lateinit variable before initialization will results in UninitializedPropertyAccessException.

The output will be:

false
true

Note that lateinit modifier could be used only on non-primitive types and on property that does not have a custom getter or setter.

When we try to access a lateinit property before it has been initialized the special exception will be thrown with all information about what went wrong.

fun main() {
    val lt = Lateinit();

    lt.test(); // throws exception
    lt.setup(); // this code will not be reached
}

This will produce the following exception:

Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property lateinitTest has not been initialized
    at Lateinit.test(Lateinit.kt:12)
    at LateinitKt.main(Lateinit.kt:19)
    at LateinitKt.main(Lateinit.kt)

4. Conclusion

In this short tutorial, we present a way to check if the lateinit variable has been initialized. Kotlin luckily provides a dedicated property that does this job well.

{{ message }}

{{ 'Comments are closed.' | trans }}