Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

Tags:

kotlin

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?

like image 894
frankelot Avatar asked Jun 16 '17 18:06

frankelot


People also ask

What is smart cast in Kotlin?

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.

Is kotlin an operator?

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.


2 Answers

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:

  1. Use a local variable with smart cast:

     val node = left  if (node != null) {      queue.add(node)  } 
  2. 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) 
  3. 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.

like image 193
mfulton26 Avatar answered Sep 20 '22 17:09

mfulton26


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 !! 
like image 36
Radesh Avatar answered Sep 18 '22 17:09

Radesh