Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...