kotlin - 智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,

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

我知道 left 是可变变量,但我明确检查 left != null 并且 left 类型Node 那么为什么不能将它智能转换为那种类型呢?

我怎样才能优雅地解决这个问题?

最佳答案

在执行 left != nullqueue.add(left) 之间,另一个线程可能已将 left 的值更改为 null.

要解决此问题,您有多种选择。以下是一些:

  1. 通过智能转换使用局部变量:

     val node = left
     if (node != null) {
         queue.add(node)
     }
    
  2. 使用 safe call例如以下之一:

     left?.let { node -> queue.add(node) }
     left?.let { queue.add(it) }
     left?.let(queue::add)
    
  3. 使用 Elvis operator与 return至return从封闭函数开始:

     queue.add(left ?: return)
    

    请注意,breakcontinue 可以类似地用于循环内的检查。

关于kotlin - 智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,此时本可以更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44595529/

相关文章:

kotlin - 在 Kotlin 中按多个字段对集合进行排序

inheritance - 在 Kotlin 中扩展数据类

kotlin - 为什么我们使用 "companion object"作为 Kotlin 中 Jav

kotlin - Kotlin 中的惯用登录方式

kotlin - 在 Kotlin 中试用资源

kotlin - 如何在 Kotlin 中将 String 转换为 Long?

kotlin - 如何将 Kotlin 的 MutableList 初始化为空 MutableLis

dictionary - 如何在 Kotlin 中将列表转换为 map ?

collections - Kotlin 的列表缺少 "add"、 "remove"、 map 缺少

design-patterns - 如何在 Kotlin 中实现 Builder 模式?