skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search