Categories
Programming

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

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

val result = value1 ?: value2

than

if (value1 != null) {
  result = value1
} else {
  result = value2
}

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

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

Comments are closed.