Thuta Learning
Kotlin
BasicProgrammingBeginner

Safe Calls & Elvis Operator

KotlinLesson 1030 min

What you'll walk away with

  • Use ?. to call members on nullable values and predict that the result type becomes nullable
  • Provide defaults and early exits with ?:, including return and throw on its right-hand side
  • Chain several safe calls and explain where the chain stops
  • Use ?.let and recognise the trap that appears when you combine let with an elvis

Explain it simply

Explain it simply

Picture a corridor of doors, and behind each door there may or may not be someone home. The ?. (safe call) is a polite knock: if nobody answers, you do not break the door down, you simply walk away with the answer null. The ?: (Elvis operator) is the "or else use this" part that supplies a replacement answer.

Used together, these two operators turn a long staircase of if (x != null) into one line. They help most when you work with data that may be missing, such as API responses, optional profile fields and database columns.

Problem → Why → Solution

The problem: null checks pile up into a pyramid

Say you want the length of a user's city name. The user may be missing, the user's address may be missing, and the address's city may be missing. With the null checks from the last lesson you get three nested ifs, and the one line you care about (city.length) is buried in the innermost block. Using !! shortens it, but crashes as soon as anything is null.

pyramid.kt
class Address(val city: String?)
class User(val address: Address?)

fun cityLength(user: User?): Int {
    if (user != null) {
        val address = user.address
        if (address != null) {
            val city = address.city
            if (city != null) {
                return city.length
            }
        }
    }
    return 0
}

Why is a better tool needed?

Every optional level adds another null check, and the code becomes hard to read. The intention is one sentence: "if everything is present take the length, otherwise 0". Kotlin lets you say "carry on only if present" with ?. and "otherwise use this" with ?:, so the same logic fits on one line.

Core concept: ?. stops the chain, ?: fills the gap

a?.b gives a.b when a is not null, and when a is null it skips the call to b and gives null instead. That makes the result type nullable: if name is a String?, then name?.length is an Int?. Assigning it to an Int, as in val n: Int = name?.length, produces: initializer type mismatch: expected 'Int', actual 'Int?'. Using an operator such as + 1 directly on the result gives: operator call is prohibited on a nullable receiver of type 'Int?'. Use '?.'-qualified call instead.

Safe calls chain: user?.address?.city?.length. As soon as any link is null, the remaining calls are skipped and the whole chain evaluates to null. Every link whose receiver is nullable needs its own ?.; leave one out and it will not compile. Adding a ?. where the receiver can never be null still compiles; it is merely redundant, and an IDE usually underlines it.

a ?: b (the Elvis operator) gives a when a is not null and b when it is. The right side is only evaluated when needed: if a is present, b never runs. When b is non-null the whole expression is non-null too, so val len: Int = name?.length ?: 0 is valid. The right side can also be return, throw, break or continue, so val clean = text?.trim() ?: return "(empty)" leaves the function immediately when there is nothing to work with. error("message") fits there too: it throws an IllegalStateException.

?.let { } runs its block only when the value is present. Inside the block, it is non-null, and the result is the block's last expression (or null when the value was missing). For simple jobs an if (x != null) is often clearer, so reach for let when you want "do this only if present" without introducing a variable that outlives the block. The table below puts all of these side by side.

OperatorMeaningResult type
a?.bCall b on a, or null if a is nullb's type made nullable
a ?: ba if present, otherwise bNon-null if b is non-null
a!!a, or a crash if it is nullNon-null
a?.let { ... }Run the block only if a is presentBlock result, or null
Mental model: knock, then fall back
  1. Each ?. asks: is anything there?
  2. If not, the whole chain becomes null
  3. ?: replaces that null with a fallback
  4. The fallback may also exit the function

?. carries null forward; only ?: or a check actually ends it.

General pattern

kotlin
val a: Int? = value?.member              // null if value is null
val b: Int = value?.member ?: fallback   // fallback replaces null
val c = value?.member ?: return result   // leave the function early
val d = value ?: throw SomeException()   // or fail loudly
value?.let { println(it) }               // runs only when value exists

The first line keeps the result nullable, the second supplies a default so it becomes non-null, the third and fourth put return or throw on the right of ?: so a missing value leaves the function, and the last runs a block only when the value exists.

Example: a safe call, an elvis and a let

This program runs a null name through a safe call and an elvis, transforms a present string with a chain, and finishes with a let. Think about why a null name does not crash and still produces two lines of output.

SafeCalls.kt
fun main() {
    val name: String? = null
    val length = name?.length
    println("Length: $length")

    val displayName = name ?: "Guest User"
    println("Welcome, $displayName")

    val typed: String? = "  Hla  "
    println(typed?.trim()?.uppercase())
    typed?.let { println("Raw length ${it.length}") }
}

Code breakdown

  1. Safe call on nullval length = name?.length

    name is null, so .length is never called and the result is null. The type of length is Int?, not Int.

  2. Null in a templateprintln("Length: $length")

    A null inside a string template becomes the text "null", so the line prints Length: null.

  3. Elvis defaultval displayName = name ?: "Guest User"

    name is null, so the right side "Guest User" is used. displayName is a plain String (non-null), so later code needs no null checks.

  4. Chained safe callsprintln(typed?.trim()?.uppercase())

    typed holds " Hla ", so trim() and uppercase() run in turn and give HLA. The first ?. makes the whole chain nullable, which is why the second link is written as ?. too.

  5. let for a present valuetyped?.let { println("Raw length ${it.length}") }

    typed is present, so the block runs and it is a non-null String. The text has 7 characters counting two spaces on each side, so it prints "Raw length 7".

You should see
Length: null
Welcome, Guest User
HLA
Raw length 7
How user?.address?.city?.length stops
  1. user null? Stop with null
  2. address null? Stop with null
  3. city null? Stop with null
  4. All present: give city.length

Every link present

Int with the real length

Any link null

null, so use ?: for a default

Closing a chain with a fallback, and early exit

This code replaces the pyramid from the problem section. cityOf closes the whole chain with ?: and a fallback of "unknown city". firstWord puts a return after ?:, so when text is null the function leaves at once, and below that line clean is a non-null String. The small classes are plain holders of values; classes get their own lessons later.

Chains.kt
class Address(val city: String?, val zip: String?)
class User(val name: String?, val address: Address?)

fun cityOf(user: User?): String = user?.address?.city ?: "unknown city"

fun firstWord(text: String?): String {
    val clean = text?.trim() ?: return "(empty)"
    if (clean.isEmpty()) return "(blank)"
    return clean.split(" ").first()
}

fun main() {
    val full = User("Aye", Address("Mandalay", "05011"))
    val noAddress = User("Su", null)
    val noCity = User(null, Address(null, "11181"))
    println(cityOf(full))
    println(cityOf(noAddress))
    println(cityOf(noCity))
    println(cityOf(null))
    println(firstWord("  hello world "))
    println(firstWord("   "))
    println(firstWord(null))
    println(full.address?.zip?.length)
    println(noAddress.address?.zip?.length)
}

The output is Mandalay, unknown city three times (no address, no city, no user), hello, (blank), (empty), 5 and null. Notice that " " gives (blank), not (empty): a string of spaces is not null. Null and an empty string are two different situations.

The trap in combining ?.let with an elvis

x?.let { ... } ?: fallback looks like an if-else, but it is not. The elvis tests the result of the let, so if the block itself returns null the fallback runs even though x was present. In the example below a zip is supplied, but lookupCity returns null for an unknown zip, so the misleading message "no zip given" is printed. The second form keeps the two cases apart and is correct.

LetTrap.kt
fun lookupCity(zip: String): String? = if (zip == "11181") "Yangon" else null

fun main() {
    val zip: String? = "99999"

    // trap: the block returns null, so the elvis runs as well
    zip?.let { lookupCity(it) } ?: println("no zip given")

    // clearer: handle the two cases separately
    if (zip == null) {
        println("no zip given")
    } else {
        println(lookupCity(zip) ?: "unknown zip")
    }
}

The output is "no zip given" followed by "unknown zip". The first line is wrong: a zip was supplied and simply not found. Writing the if-else is plainer, but it states the intent more honestly.

In real projects

Where this shows up in real projects

Code that handles JSON responses with optional fields is full of lines like response.user?.profile?.avatarUrl ?: DEFAULT_AVATAR. Reading configuration looks like System.getenv("PORT")?.toIntOrNull() ?: 8080: if the variable is missing, or present but not a number, the default port is used. One such line replaces four or five null checks.

The same operator drives guard clauses. val user = repository.find(id) ?: return leaves the function when no user exists, and for the rest of the function user is non-null. Or you can fail loudly with ?: throw IllegalArgumentException("unknown user $id"). This pattern cuts nesting and keeps the normal path lined up at the left edge, which makes code reviews easier. Just make sure the fallback value does not change the meaning of the result, as the mistakes below show.

Common mistakes

Common mistakes

1. Assuming the result of ?. is non-null

val n: Int = a?.length does not compile: initializer type mismatch: expected 'Int', actual 'Int?'. Let the type be inferred with val n = a?.length, or add a fallback with ?: 0. s?.length + 1 fails in the same way, so write (s?.length ?: 0) + 1.

2. Treating let plus elvis as an if-else

In x?.let { f(it) } ?: log("none"), if f(it) returns null then "none" is logged even though x was present. When the block can return null, or the fallback has a side effect, use if (x != null) ... else ... instead.

3. Using ?: to hide missing data

Writing val price = item?.price ?: 0 quietly turns an item with an unknown price into a free one. A default suits choices that are yours to make, such as a page size, but for important data like amounts, prices or ids it is better to fail loudly with ?: error("price is missing").

4. Putting !! back after ?.

user?.address!!.city throws away the benefit of the safe call and crashes when address is null. If you mix ?. and !! in one chain you should be able to explain why null is impossible at that link; if you cannot, keep using ?.

Best practices

Best practices

  • End a chain with ?: and deal with null in one place, so the rest of the code sees a non-null value.
  • When work cannot continue without the value, leave early with ?: return or ?: error("...") to cut nesting.
  • Use let only when it is clearer than a plain if (x != null), and do not follow a let with an elvis.

Mini challenge

Mini challenge: tidying a contact list

A contact list mixes entries with no name, no email, or a null contact altogether. Use ?. and ?: to produce each contact's display name and email domain.

  • label(contact: Contact?) returns the trimmed name, or "Anonymous" when the contact or the name is null
  • domainOf(contact: Contact?) returns the part after @ in lowercase
  • If the contact or the email is null, return "no email" using ?: return; if there is no @, return "invalid email"
  • main loops over a list that includes a null and prints "label -> domain"
Contacts.kt
class Contact(val name: String?, val email: String?)

fun label(contact: Contact?): String {
    // TODO: contact?.name?.trim() with a fallback of "Anonymous"
}

fun domainOf(contact: Contact?): String {
    // TODO: val email = ... ?: return "no email"
    // TODO: find the '@' with indexOf; return "invalid email" if it is missing
    // TODO: return the lowercase text after the '@'
}

fun main() {
    // TODO: build a list of contacts that includes a null, then print each one
}

Expected: The program should print: Aye -> example.com Anonymous -> mail.org Hla -> no email Min -> invalid email Anonymous -> no email

Show hint

Take the email with val email = contact?.email ?: return "no email", and below that line email is a non-null String. indexOf('@') returns -1 when nothing is found, then substring(at + 1).lowercase() gives the domain. A list that includes null has the element type Contact?.

Show solution
Contacts.kt
class Contact(val name: String?, val email: String?)

fun label(contact: Contact?): String {
    val name = contact?.name?.trim()
    return name ?: "Anonymous"
}

fun domainOf(contact: Contact?): String {
    val email = contact?.email ?: return "no email"
    val at = email.indexOf('@')
    if (at < 0) return "invalid email"
    return email.substring(at + 1).lowercase()
}

fun main() {
    val contacts = listOf(
        Contact("  Aye ", "aye@Example.COM"),
        Contact(null, "su@mail.org"),
        Contact("Hla", null),
        Contact("Min", "not-an-email"),
        null,
    )
    for (contact in contacts) {
        println("${label(contact)} -> ${domainOf(contact)}")
    }
}

Quick quiz 1 / 3

With val s: String? = null, what is n in val n = s?.length ?: -1?

Quick quiz 2 / 3

If name is a String?, what is the type of name?.length?

Quick quiz 3 / 3

With zip = "99999" and lookupCity("99999") returning null, what does zip?.let { lookupCity(it) } ?: println("no zip") print?

What to remember

  • a?.b gives null and skips b when a is null, and the result type becomes nullable.
  • A chain of ?. stops at the first null and the whole chain becomes null.
  • a ?: b evaluates b only when a is null, and b may be return, throw or error().
  • ?.let runs its block only when the value exists, but following a let with an elvis also runs the fallback when the block returns null.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Safe Calls & Elvis Operator | Thuta Learning