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.
2
Answers
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.
Checking nullable boolean against
true
orfalse
is an "official" Kotlin idiom:Here is the relevant discussion regarding the idiom, including opinions for and against it.