liveBook · Manning

Nullish coalescing operator

As explained in Kotlin in Action, 2E

The Elvis operator `?:` evaluates its left operand when non-null and otherwise evaluates and returns its right operand.

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

How Kotlin in Action, 2E covers it

How deep it goes
Explains evaluation, safe-call combinations, defaults, and throw-based validation through compact Kotlin examples.
Examples
Uses nullable string lengths, names, nested company addresses, shipping labels, and missing person ages.
What it assumes
Assumes nullable-type syntax and safe calls while treating null handling as Kotlin’s alternative to unchecked null failures.
What you can do after
Apply it to replace null with defaults or enforce preconditions using return and throw expressions.
How it connects
Connects nullable types with safe calls, non-null assertions, let, and safe casts.

Also explained in

Compare how 3 books explain nullish coalescing operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.