本文介绍了无法将类型强制转换为“类型",因为“变量"是可变属性,到那时可能已经更改了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

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
         }
    }

我知道left是可变变量,但是我明确检查了left != null并且leftNode类型,所以为什么不能将其智能转换为该类型?

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? :)

推荐答案

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

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. 使用局部变量进行智能强制转换:

  1. Use a local variable with smart cast:

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

  • 使用安全呼叫,例如一个以下:

  • 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)
    

  • Elvis运算符 return 以便从封闭函数中尽早返回:

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

    queue.add(left ?: return)
    

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

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

    这篇关于无法将类型强制转换为“类型",因为“变量"是可变属性,到那时可能已经更改了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    1403页,肝出来的..

  • 09-06 18:48