How to check if a “lateinit” variable has been initialized?

前端 未结 8 670
执念已碎
执念已碎 2020-11-29 15:37

I wonder if there is a way to check if a lateinit variable has been initialized. For example:

class Foo() {

    private lateinit var myFile: Fi         


        
8条回答
  •  半阙折子戏
    2020-11-29 16:21

    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@YourClassName::variableName.isInitialized
    

    Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be superclass or any other class which is instantiated), for ex:

    class Test {
        lateinit var str:String
    }
    

    And to check if str is initialized:

    What we are doing here: checking isInitialized for field str of Test class in Test2 class. And we get an error backing field of var is not accessible at this point. Check a question already raised about this.

提交回复
热议问题