智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,此时可能已经更改 [英] Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

查看:15
本文介绍了智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,此时可能已经更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin 新手问,为什么下面的代码不能编译?":

var left:节点?= 空有趣的表演(){如果(左!= null){queue.add(left)//此处出错}}

<块引用>

智能转换到 'Node' 是不可能的,因为 'left' 是可变的这个时候可能已经改变的属性

我知道 left 是可变变量,但我明确检查了 left != nullleft 类型Node 那么为什么不能将其智能转换为该类型?

我该如何优雅地解决这个问题?

解决方案

在执行 left != nullqueue.add(left) 之间,另一个线程可能已经改变leftnull 的值.

要解决此问题,您有多种选择.这里有一些:

  1. 在智能转换中使用局部变量:

     val 节点 = 左如果(节点!= null){queue.add(节点)}

  2. 使用安全调用,例如以下内容:

     left?.let { node ->队列.添加(节点)}left?.let { queue.add(it) }left?.let(queue::add)

  3. 使用 Elvis operatorreturn返回 早于封闭函数:

     queue.add(left ?: return)

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

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?

解决方案

Between execution of left != null and queue.add(left) another thread could have changed the value of left to null.

To work around this you have several options. Here are some:

  1. Use a local variable with smart cast:

     val node = left
     if (node != null) {
         queue.add(node)
     }
    

  2. Use a safe call such as one of the following:

     left?.let { node -> queue.add(node) }
     left?.let { queue.add(it) }
     left?.let(queue::add)
    

  3. Use the Elvis operator with return to return early from the enclosing function:

     queue.add(left ?: return)
    

    Note that break and continue can be used similarly for checks within loops.

这篇关于智能转换为 'Type' 是不可能的,因为 'variable' 是一个可变属性,此时可能已经更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆