Open In App
Related Articles

How to Check if a “lateinit” Variable Has Been Initialized or Not in Kotlin?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 we are sure that the variable will be initialized before using it. If we don’t initialize a lateinit variable before using it gives an error of “lateinit property has not been initialized”. 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.

You can easily do this by:

::variableName.isInitialized

or:

this::variableName.isInitialized

But if you are inside a listener or inner class, do this:

this@OuterClassName::variableName.isInitialized

For Example:

Kotlin

class Tutorial {
  
    lateinit var tutorialName : String
  
    fun initializeName(){
        println(this::tutorialName.isInitialized)
          
        // initializing name
        tutorialName = "GFG Android Course" 
        println(this::tutorialName.isInitialized)
    }
}
  
fun main() {
    Tutorial().initializeName();
}

                    

Output:

false

true


Last Updated : 23 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads