?: is not ? :

Why whitespace matters

Thomas Künneth
Tommis Programming Blog
2 min readDec 16, 2019

--

Question marks and colons in different colors and sizes
?: and ? : is not the same

Kotlin has a nice feature called the Elvis operator. This binary operator returns its first operand if it is not null, otherwise the second one. To see it in action, please take a look at this code snippet:

val person = object { val name = null}
val s = person.name ?: “???”
println(s)

It will print ???. If we assigned name to 42, the output would be 42. Please note that there is no whitespace between ? and :. If you try to add one Kotlin complains. Why am I telling this? Java doesn’t know Elvis, but offers a somewhat more flexible variant called conditional operator.

Person person = new Person();
String s = person.name != null ? person.name : “???”;
System.out.println(s);

The first operand is the condition, the second one is returned if that one is true. Otherwise the last operand becomes the result of the expression. If the first and second arguments are the same, the expression is a little awkward to read. To remedy this, some languages make the second operand optional.

Now, back to Elvis. In some languages the semantics differs. There, the first argument is not expected to be not null (as in Kotlin) but true. This makes it more similar to the conditional operator, which, by the way, Kotlin does not know. Still, in Kotlin if is not a statement but an expression, so it can be seen as a replacement.

Now, you may be asking… Why Elvis? The name is said to refer to its resemblance to an emoticon of Elvis Presley, more precisely, his hair.

A previous version of this article was published on my Blogger.com blog called Tommis Blog. I deleted the blog in the wake of the GDPR (General Data Protection Regulation), so my original post is no longer available.

If not stated otherwise images are © Thomas Künneth

--

--

Thomas Künneth
Tommis Programming Blog

Google Developer Expert for Android. Author. Speaker. Listener. Loves writing.