Elvis operator

Why “?:” is called Kotlin’s “Elvis operator”

by Joey deVilla on November 13, 2017

At Victoria Gonda’s presentation on Kotlin at DevFest Florida 2017, she talked about many of Kotlin’s language features. (Be sure to check out the slides from her presentation, Kotlin Uncovered!)

When she got to the “Elvis operator”?: — there were murmurs in the crowd, and I could hear people whispering “why’s it called that?”. Hopefully, the photo above answers the question: it looks like an emoticon for Elvis.

The more formal name for the Elvis operator is the null coalescing operator, and it’s a binary operator that does the following:

  • It returns the first operand if it’s non-null,
  • otherwise, it returns the second operand.

It’s far more elegant to write

than

And in case you iOS developers were wondering, Swift has a null coalescing operator: it’s ??.

{ 0 comments }