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

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

    To check if a lateinit var were initialised or not use a .isInitialized on the reference to that property:

    if (foo::bar.isInitialized) {
        println(foo.bar)
    }
    

    This checking is only available for the properties that are accessible lexically, i.e. declared in the same type or in one of the outer types, or at top level in the same file.

提交回复
热议问题