How to check if a "lateinit" variable has been initialized?

How to check if a lateinit variable has been initialized?

In Kotlin, the lateinit keyword is used for those variables which are initialized after the declaration or we can say that the variable which is late initialized is called a lateinit variable.

The lateinit keyword is used when the developer is sure that the variable will be initialized before using it. For example, properties can be initialized through dependency injection or in a setup method of a unit test. So, in these cases, we can use the lateinit variable.

But there are cases when you try to access the not initialized lateinit variable and this, in turn, result in the following error:

lateinit property has not been initialized

So, in Kotlin 1.2 version, an improvement was made in the lateinit. Now, you can check if the lateinit variable has been initialized or not before using it with the help of isInitialized method. This method will return true if the lateinit property has been initialized otherwise it will return false. For example:

class Person {
    lateinit var name: String

    fun initializeName() {
        println(this::name.isInitialized)
        name = "MindOrks" // initializing name
        println(this::name.isInitialized)
    }
}
fun main(args: Array<String>) {
    Person().initializeName()
}

The above function will return the following:

false
true

In this way, you can check if the lateinit variable has been initialized or not.

You can find Open-Source projects by MindOrks from here.

Have a look at our Interview Kit for company preparation.

Do share this tutorial with your fellow developers to spread the knowledge. You can read more blogs on Android on our blogging website.

Apply Now: MindOrks Android Online Course and Learn Advanced Android

Happy Learning :)

Team MindOrks!