智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,此时可能已经更改

问题:

And the Kotlin newbie asks, "why won't the following code compile?": Kotlin 新手会问,“为什么下面的代码不能编译?”:

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?我知道left是可变变量,但我明确检查left != null并且leftNode类型,所以为什么不能将它智能转换为该类型?

How can I fix this elegantly?我该如何优雅地解决这个问题?


解决方案:

参考一: https://en.stackoom.com/question/317Kj
参考二: https://stackoom.com/question/317Kj
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章