Kotlin:必需:kotlin.Boolean.找到:kotlin.Boolean? [英] Kotlin: Required: kotlin.Boolean. Found: kotlin.Boolean?

查看:1065
本文介绍了Kotlin:必需:kotlin.Boolean.找到: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()
}

这样,如果subscribernullsubsriber?.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屋!

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