Kotlin:必需:kotlin.Boolean.找到:kotlin.Boolean? [英] Kotlin: Required: kotlin.Boolean. Found: kotlin.Boolean?
问题描述
我写了如下条件
if (subsriber?.isUnsubscribed && isDataEmpty()) {
loadData()
}
因为我的订阅者可能为空.显示上面的标题错误.所以我将其投射如下
As my subscriber could be null. The above title error displayed. So I cast it as below
if (subsriber?.isUnsubscribed as Boolean && isDataEmpty()) {
loadData()
}
看起来不太好.有更好的方法吗?
It looks not as nice. Is there a better way of doing this?
推荐答案
我通常使用?:
运算符解决这种情况:
I usually resolve this situation with the ?:
operator:
if (subsriber?.isUnsubscribed ?: false && isDataEmpty()) {
loadData()
}
这样,如果subscriber
是null
,subsriber?.isUnsubscribed
也是null
,并且subsriber?.isUnsubscribed ?: false
求值为false
,这有望达到预期的结果,否则请切换到?: true
.
This way, if subscriber
is null
, subsriber?.isUnsubscribed
is also null
and subsriber?.isUnsubscribed ?: false
evaluates to false
, which is hopefully the intended result, otherwise switch to ?: true
.
也使用as Boolean
强制转换为可空类型是不安全,并且将引发异常如果遇到null
.
Also casting a nullable type with as Boolean
is unsafe and will throw an exception if null
is encountered.
这篇关于Kotlin:必需:kotlin.Boolean.找到:kotlin.Boolean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!