And the Kotlin newbie asks, "why won't the following code compile?":
var left: Node? = null fun show() { if (left != null) { queue.add(left) // ERROR HERE } }
Smart cast to 'Node' is impossible, because 'left' is a mutable property that could have been changed by this time
I get that left
is mutable variable, but I'm explicitly checking left != null
and left
is of type Node
so why can't it be smart-casted to that type?
How can I fix this elegantly?
Smart cast is a feature in which the Kotlin compiler tracks conditions inside of an expression. If the compiler finds a variable that is not null of type nullable then the compiler will allow to access the variable.
Kotlin has a set of operators to perform arithmetic, assignment, comparison operators and more. You will learn to use these operators in this article. Operators are special symbols (characters) that carry out operations on operands (variables and values). For example, + is an operator that performs addition.
Between execution of left != null
and queue.add(left)
another thread could have changed the value of left
to null
.
To work around this you have several options. Here are some:
Use a local variable with smart cast:
val node = left if (node != null) { queue.add(node) }
Use a safe call such as one of the following:
left?.let { node -> queue.add(node) } left?.let { queue.add(it) } left?.let(queue::add)
Use the Elvis operator with return
to return early from the enclosing function:
queue.add(left ?: return)
Note that break
and continue
can be used similarly for checks within loops.
1) Also you can use lateinit
If you sure do your initialization later on onCreate()
or elsewhere.
Use this
lateinit var left: Node
Instead of this
var left: Node? = null
2) And there is other way that use !!
end of variable when you use it like this
queue.add(left!!) // add !!
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