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?
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.
Another way to resolve this issue is to explicitly check if the expression is true
:
if (subsriber?.isUnsubscribed == true && isDataEmpty()) {
loadData()
}
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
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 !!.
.