What does ?: do in Kotlin?

February 10, 2019

One of the weird symbols that you may see in Kotlin code is ?:, which is known as the elvis operator. What does it do though? Basically what it does is that it provides an alternative value if an optional value returns null.

Let's see an example:

val x: String? = "foo"
val y: String = x ?: "bar"      // "foo", because x was non-null    

val a: String? = null
val b: String = a ?: "bar"      // "bar", because a was null