如何处理不为空的可空变量?

How to deal with nullable variables that are not null?

考虑这段代码:

var foo: Foo? = null

if (foo != null) {
    foo!!.bar()
}

如果我省略了两个!!我收到此错误:

Smart cast to 'Foo' is impossible, because 'foo' is a mutable property that could have been changed by this time

这是关于并发的,对吧?好吧,没有并发代码可能会更改 foo.

的值

当然,它与两个一起使用!!。但是,我想知道这是否是最惯用的方法,或者是否有更好的方法,没有这两个!!

我知道在这种特殊情况下我可以 foo?.bar()。但问题是在我检查它不是 null.

之后,我是否可以以某种方式将 foo 视为 Foo 而不是 Foo?

嗯,如果 foo 是一个局部变量,这段代码就可以工作。我想,您的代码看起来有点不同,foo 是 class 的一个字段。解决方法很简单:使用 let:

foo?.let {
    it.bar()
}

let "captures" 变量的值,这样对原始变量的任何修改都不会影响传递的 lambda。此处使用安全调用仅对非空值调用 let