Kotlin: Required: kotlin.Boolean. Found: kotlin.Bo

2019-04-20 21:18发布

问题:

I wrote a condition as below

    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?

回答1:

I usually resolve this situation with the ?: operator:

if (subsriber?.isUnsubscribed ?: false && isDataEmpty()) {
    loadData()
}

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.

Also casting a nullable type with as Boolean is unsafe and will throw an exception if null is encountered.



回答2:

Another way to resolve this issue is to explicitly check if the expression is true:

if (subsriber?.isUnsubscribed == true && isDataEmpty()) {
    loadData()
}


回答3:

Also is you have just Required: kotlin.Boolean. Found: kotlin.Boolean? you can do this:

when(something?.isEmpty()) {
    true ->  {  }
    false -> {  }
    null ->  {  }
}

i know it's answered question but for future viewers can be helpful



回答4:

If subscriber is val,

subscriber != null && subscriber.isUnsubscribed && isDataEmpty()

will work. As a bonus, subscriber != null will be known inside the if block and you can call methods on subscriber without ?. or !!..



标签: kotlin