How to perform companion object lateinit is initiallize check

前端 未结 1 1683
天涯浪人
天涯浪人 2021-01-20 15:12

If I have a lateinit variable, I could check is it initialized using (this::lateInitVar.isInitialized), as shown in https://stackoverflow.com/a/47860466/3286489

Howe

相关标签:
1条回答
  • 2021-01-20 15:47

    You could extract it into a function inside the companion object:

    class MyClass {
    
        companion object {
            lateinit var myGlobalLateInit: String
    
            fun isMyGlobalLateInitInitialized() = ::myGlobalLateInit.isInitialized
        }
    
        fun settingVariable() {
            if (!isMyGlobalLateInitInitialized()) {
                myGlobalLateInit = "I am set"
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题