智能轉換爲 '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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章