Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 03 / Topic 3 of 8

Elvis operator: ?:

?: ("Elvis", because sideways the symbol looks like a smiley with a quiff) reads "or, if the left side is null, use this instead." The right side can be a plain default value, or any expression at all, including one that never returns normally — a throw, or a return from the enclosing function.

val city = cities[username] ?: "an unknown city"            // plain default

fun pincodeOrFail(username: String, pincodes: Map<String, String>): String {
    return pincodes[username] ?: throw NoSuchElementException("no pincode on file for $username")
}

The throw form type-checks because throw in Kotlin is itself an expression of type Nothing — a type that can stand in for any other type, since a throw never actually produces a value to use. The same trick works with return for an early exit out of whichever function the Elvis sits inside.

$ kotlinc 03_elvis.kt -include-runtime -d 03.jar
$ java -jar 03.jar
Namaste from Pune, asha.rao!
Namaste from an unknown city, deepa.iyer!
411001
caught: no pincode on file for deepa.iyer
pincode length for deepa.iyer = 0

The single most common idiom in idiomatic Kotlin is ?. and ?: together, on one line: reach for a value that might not exist, then decide right there what "it doesn't exist" means.

val pincodeLength: Int = pincodes["deepa.iyer"]?.length ?: 0

Full program: examples/03_elvis.kt.

Done here? The practice set for Part 3 — including the solutions — is on the part page.

Search the guide