11

Member lateinit variables initialization can be checked with:

class MyClass {
    lateinit var foo: Any
    ...
    fun doSomething() {
        if (::foo.isInitialized) {
           // Use foo
        }
    }
}

However this syntax doesn't work for local lateinit variables. Lint reports the error: "References to variables aren't supported yet". There should logically be a way to do that since lateinit variables are null internally when uninitialized.

Is there a way to check if local variables are initialized?

Nicolas
  • 6,611
  • 3
  • 29
  • 73
  • 2
    Can't reproduce this. If `foo` is optional You should use a nullable field instead of `lateinit var`. It is intended mostly for field injection or initialization that cannot be done within constructor (for example - Androids `onCreate` call). – Pawel Feb 08 '19 at 23:15
  • @Pawel But why was local lateinit introduced then? – Nicolas Feb 08 '19 at 23:24
  • Take a look at this question and the answer. This maybe a duplicate. https://stackoverflow.com/questions/47052164/unresolved-reference-unresolved-reference-isinitialized/47105843#47105843 – nPn Feb 09 '19 at 00:59
  • 2
    https://youtrack.jetbrains.com/issue/KT-21163 – Alexey Romanov Feb 09 '19 at 07:09
  • @AlexeyRomanov Thanks – Nicolas Feb 09 '19 at 13:09
  • You are not showing the code that actually produces the compiler message. In your code foo is not a local variable and the code you show will work fine in Kotlin 1.2+ – nPn Feb 10 '19 at 16:35

1 Answers1

18

The code you show in your question is actually fine in Kotlin 1.2 and beyond, since foo is an instance variable, not a local variable. The error message you report and mentioned in Alexey's comment (Unsupported [References to variables aren't supported yet]) can be triggered by a true local variable, for example in the doSomethingElse method below.

class MyClass {
    lateinit var foo: Any

    fun doSomething() {
        if (::foo.isInitialized) {  // this is fine to use in Kotlin 1.2+
           // Use foo
        }
    }
    fun doSomethingElse() {
        lateinit var bar: Any

        if (::bar.isInitialized) {  // this is currently unsupported (see link in Alexey's comment.
            // Use bar 
        }

    }

}

So it seems like this is currently unsupported. The only place that comes to mind where a lateinit local would be used would be if the local is variable captured in a lambda?

nPn
  • 16,254
  • 9
  • 35
  • 58