Learning Kotlin: Kotlin's Elvis Operator

Submitted by Robert MacLean on Tue, 07/03/2018 - 09:00

More Information

  • This is the 12th post in a multipart series.
    If you want to read more, see our series index

We are going to take a short break from the Koans and look at a cool trick I learnt today. Previously, we learnt about the safe null operator but that only helps when calling functions or properties of objects...

  1. fun ifDemo1(name:String?) {
  2.     val displayName = if (name != null) name else "Mysterious Stranger"
  3.     println("HI ${displayName}")
  4. }

In the above example, we have the name String which could be null but safe null operator (this needs a better name) can't help here... so let us look at what Kotlin calls the Elvis operator ?: and what it gives us:

  1. fun ifDemo2(name:String?) {
  2.     val displayName = name ?: "Mysterious Stranger"
  3.     println("YO ${displayName}")
  4. }

This is really cool and reminds me of SQL COALESCE where it lets you test the first value and if it is not null, it returns the first value, else it returns the second value.