Kotlin – How to negate a boolean expression when using the elvis operator in kotlin

kotlin

I want to negate the following expression:

return SpUtils.loadEMail()?.isEmpty() ?: false

If i add a ! before the expression, like

return !SpUtils.loadEMail()?.isEmpty() ?: false

The IDE(Android Studio) tells me

Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type kotlin.Boolean?

How do I negate this kinds of expressions?

Best Answer

You have problem with nullable reference.

 SpUtils.loadEMail()?.isEmpty()

This code produces value of type Boolean? that's mean expression can return an instance of Boolean or null.

I suggest following code to solve your problem:

return !(SpUtils().loadEMail()?.isEmpty() ?: false);

You trying negate Boolean? instead of Boolean, that elvis operator returns!

Related Topic