Learning Kotlin: Kotlin's Elvis Operator

Note 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 learned today. Previously, we learned about the safe null operator, but that only helps when calling functions or properties of objects:

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

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

fun ifDemo2(name: String?) {
    val displayName = name ?: "Mysterious Stranger"
    println("YO ${displayName}")
}

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