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

前端 未结 8 672
执念已碎
执念已碎 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:34

    If you have a late init property in one class and need to check if it is initialized from another class

    if(foo::file.isInitialized) // this wouldn't work
    

    The workaround I have found is to create a function to check if the property is initialized and then you can call that function from any other class.

    Example:

    class Foo() {
    
        private lateinit var myFile: File
    
        fun isFileInitialised() = ::file.isInitialized
    }
    
     // in another class
    class Bar() {
    
        val foo = Foo()
    
        if(foo.isFileInitialised()) // this should work
    }
    

提交回复
热议问题