Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a local lateinit variable is initialized

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?

like image 756
Nicolas Avatar asked Feb 08 '19 22:02

Nicolas


People also ask

How do you check if a lateInit variable is initialized or not?

Along with this modifier, Kotlin provides a couple of methods to check whether this variable is initialized or not. Use "lateInit" with a mutable variable. That means, we need use "var" keyword with "lateInit". "lateInit" is only allowed with non-NULLable data types.

How do you initialize a lateInit property?

In order to create a "lateInit" variable, we just need to add the keyword "lateInit" as an access modifier of that variable. Following are a set of conditions that need to be followed in order to use "lateInit" in Kotlin. Use "lateInit" with a mutable variable. That means, we need to use "var" keyword with "lateInit".

What happens when a field declared as lateInit is accessed before it is initialized?

Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.

Is lateInit null?

While using Lateinit , the variable can't be of the null type. Lateinit cannot be used for primitive datatypes, i.e., Long and int. If you try accessing Lateinit variables without initializing, it will throw an exception stating that it is not initialized or properly being accessed.


1 Answers

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?

like image 84
nPn Avatar answered Oct 16 '22 21:10

nPn