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?
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.
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".
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With