4

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

However if the variable is a companion object, how could I do so?

e.g.

class MyClass {

    companion object {
        lateinit var myGlobalLateInit: String
    }

    lateinit var myLocalLateInit: String

    fun settingVariable() {
        if (!this::myLocalLateInit.isInitialized) {
            myLocalLateInit = "I am set"
        }

        if (!MyClass::myGloablLateInit.isInitialized) { // This line will error out. How could I set it?
            myGloablLateInit = "I am set"
        }

    }

}
Elye
  • 53,639
  • 54
  • 212
  • 474
  • Personally, I'd just not make it lateinit and set it to null instead, and check for that – Joozd Mar 09 '20 at 08:52

1 Answers1

7

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"
        }

    }

}
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487