Kotlin

Safe Call Chain + Elvis Default

admin by @admin ADMIN
1h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`?.` is the safe-call operator — short-circuits to `null` at the first null in a chain. Pair with `?:` (Elvis) for "this or a default". Replaces nested if-not-null ladders.
Kotlin
Raw
data class Address(val city: String?, val zip: String?)
data class User(val name: String, val address: Address?)

fun main() {
    val user: User? = User("Alice", Address("Austin", null))

    // The whole chain short-circuits to null on any null link
    val city: String? = user?.address?.city
    println(city)                                // Austin

    // Elvis: replace null with a default value
    val display = user?.address?.city ?: "unknown"
    println(display)                             // Austin

    // Elvis with throw: fail fast if any link is null
    fun requireCity(u: User?): String =
        u?.address?.city ?: throw IllegalArgumentException("city required")

    // Elvis with return: early-exit out of the enclosing function
    fun describeOrBail(u: User?) {
        val zip = u?.address?.zip ?: return    // returns from describeOrBail
        println("zip = $zip")
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.