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

asked9 years ago
last updated5 years ago
viewed157.5k times
Up Vote394Down Vote

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?