Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 740
Lukas Lechner Avatar asked Dec 17 '15 10:12

Lukas Lechner


People also ask

How do I change the Boolean value in Kotlin?

Boolean to String You can use toString() function to convert a Boolean object into its equivalent string representation. You will need this conversion when assigning a true or false value in a String variable.

Can Boolean be null Kotlin?

Kotlin's nullable Boolean type Boolean? is pretty similar to Java's Boolean type. Both may have a true, false, or null value.

How do you use the NOT operator in Kotlin?

The NOT Operator: ! The logical NOT operator ( ! ) evaluates the value of a Boolean expression and then returns its negated value.


1 Answers

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!

like image 159
Ruslan Avatar answered Sep 18 '22 16:09

Ruslan