Home > other >  If check with nullable boolean and elvis operator fails inspection check, why?
If check with nullable boolean and elvis operator fails inspection check, why?

Time:10-15

in Android Studio I wrote the following in a function:

if (startTimes.value?.containsKey(name)?:false) {
    return startTimes?.value?.get(name)
}

Android Studio highlights the contents of the if with a warning with the message Equality check should be used instead of elvis for nullable boolean check and suggests I replace it with:

if (startTimes.value?.containsKey(name) == true) {
    return startTimes?.value?.get(name)
}

Why is the second preferred by the IDE? As far as I can tell they're logically the same.

CodePudding user response:

The first one is two steps. It does a null check and then evaluates to a value. The second evaluates the value directly.

Personally, I think the second is much easier to reason about.

"Is x or else if x is null then false, true?"

versus

"Is x exactly true?"

Aside from that, there are some idioms that the compiler tries to push on you, I think in an effort to make code more readable in general. If most people use the same idioms, it's easier to read each others' code.

CodePudding user response:

Checking nullable boolean against true or false is an "official" Kotlin idiom:

Nullable Boolean

val b: Boolean? = ... 
if (b == true) {
    ... 
} else {
    // `b` is false or null 
}

Here is the relevant discussion regarding the idiom, including opinions for and against it.

  • Related