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

前端 未结 8 628
执念已碎
执念已碎 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
    }
    
    0 讨论(0)
  • 2020-11-29 16:35

    There is a lateinit improvement in Kotlin 1.2 that allows to check the initialization state of lateinit variable directly:

    lateinit var file: File    
    
    if (this::file.isInitialized) { ... }
    

    See the annoucement on JetBrains blog or the KEEP proposal.

    UPDATE: Kotlin 1.2 has been released. You can find lateinit enhancements here:

    • Checking whether a lateinit var is initialized
    • Lateinit top-level properties and local variables
    0 讨论(0)
提交回复
热议问题