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

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

    Accepted answer gives me a compiler error in Kotlin 1.3+, I had to explicitly mention the this keyword before ::. Below is the working code.

    lateinit var file: File
    
    if (this::file.isInitialized) {
    
        // file is not null
    }
    

提交回复
热议问题