Search code examples
kotlinkotlin-null-safety

Effectiveness of ?: , null-safety and Elvis operator?


I am referring to the Null-Safety in Kotlin:

A colleague of mine writes always like:

bob ?: return
bob.department ?: return
bob.department.head ?: return
bob.department.head.name()

Readability is his argument. This is for me not very Kotlin like and more overelaborated. Of course I prefer:

bob?.department?.head?.name()

Some arguments/docs/links not using upper way would be very helpful.

I would like to know if there are any disadvantages using upper way? Also, I can imagine that some compiler optimization won't work very well, doing the upper way?

EDIT: According to SVN the history tells:

if (bob != null) {
    if (bob.department != null) {
        if (bob.department.head != null) bob.department.head.name()
    }
}

Solution

  • Your version means something different: if any of the relevant values are null, your version evaluates to null without evaluating the rest of the expression, while your colleague's returns immediately without executing the rest of the function.

    (Of course, if that's the end of the function anyway, the effect may be the same; we can't tell without seeing some context.)

    So which one to prefer depends on whether a null value should abort everything following.

    In general, though, your version is much more common in my experience.  It also has two advantages: it's more concise (which, when all other things are equal, is a Good Thing™ IMHO) with less repetition (so following DRY); and it's less likely to cause surprises when someone later adds extra lines afterward, so they don't have to track back and find out why they're not being executed.

    As for readability, lines like yours are a common idiom in Kotlin, and so developers really ought to find them readable enough.  In fact, the ability to avoid long chains of tests like your colleague's (as are needed in Java) is one of the main benefits of the ?. safe-call operator!