問題:
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
並且left
是Node
類型,所以爲什麼不能將它智能轉換爲該類型?
How can I fix this elegantly?我該如何優雅地解決這個問題?
解決方案:
參考一: https://en.stackoom.com/question/317Kj參考二: https://stackoom.com/question/317Kj