Kotlin’s nullish coalescing operator, written ?: and commonly called the Elvis operator, selects the left expression when it is non-null; otherwise, it evaluates and returns the right expression. section 7.5
Provide a default value
fun strLenSafe(s: String?): Int = s?.length ?: 0 println(strLenSafe("abc")) // 3 println(strLenSafe(null)) // 0 The safe-call operator produces a nullable length, and ?: supplies zero when the string or its length is null. section 7.5
Use the operator for several concise null-handling patterns:
- Assign a readable fallback: val recipient: String = name ?: "unnamed". section 7.5
- Traverse nullable properties and replace a missing result: company?.address?.country ?: "Unknown". section 7.5
- Stop execution when a required value is absent: person.company?.address ?: throw IllegalArgumentException("No address"). section 7.5
Choose the oldest person
data class Person(val name: String, val age: Int? = null) val oldest = persons.maxBy { it.age ?: 0 } When Bob’s omitted age becomes null, ?: supplies zero, allowing Alice’s age to determine the result. section 1.1
Listing 7.5 Using throw together with the Elvis operator
class Address(val streetAddress: String, val zipCode: Int,
val city: String, val country: String)
class Company(val name: String, val address: Address?)
class Person(val name: String, val company: Company?)
fun printShippingLabel(person: Person) {
val address = person.company?.address
?: throw IllegalArgumentException("No address") #1
with (address) { #2
println(streetAddress)
println("$zipCode $city, $country")
}
}
fun main() {
val address = Address("Elsestr. 47", 80687, "Munich", "Germany")
val jetbrains = Company("JetBrains", address)
val person = Person("Dmitry", jetbrains)
printShippingLabel(person)
// Elsestr. 47
// 80687 Munich, Germany
printShippingLabel(Person("Alexey", null))
// java.lang.IllegalArgumentException: No address
}
Inspect a complete shipping-label example where a safe-call chain either yields an address or throws a meaningful exception. section 7.5


