← Back to Kotlin Course | Chapter 5: Null Safety | Lesson 2 of 6

Safe Call Operator

The safe call operator lets you ask a possibly-empty box for something, and if the box really is empty, it just quietly gives you nothing back instead of crashing.

Basic Safe Call

?. calls a method or property only when the receiver is not null; if the receiver is null, the whole expression short-circuits to null without throwing.

Example: Basic Safe Call

markup
fun main() {
    val name: String? = "Kotlin"
    val nullName: String? = null
    println(name?.length)
    println(nullName?.length)
}

Chaining Safe Calls

Multiple ?. operators can be chained together, such as user?.address?.city, and the entire chain evaluates to null the moment any part of it is null.

Example: Chaining Safe Calls

markup
data class Address(val city: String)
data class Person(val name: String, val address: Address?)

fun main() {
    val personWithAddress = Person("Ana", Address("Berlin"))
    val personWithoutAddress = Person("Bo", null)
    println(personWithAddress.address?.city)
    println(personWithoutAddress.address?.city)
}

Safe Calls with Function Calls

A safe call also works before calling a function, so text?.trim() only runs trim() if text is not null, producing null otherwise.

Example: Safe Calls with Function Calls

markup
fun main() {
    val input: String? = "  hello  "
    val trimmed = input?.trim()
    println("Trimmed: $trimmed")
}

Safe Calls in Conditions

Safe calls combine naturally with equality checks, such as if (text?.length == 0), since comparing null to an Int simply evaluates to false rather than throwing.

Example: Safe Calls in Conditions

markup
fun main() {
    val text: String? = null
    if (text?.length == 0) {
        println("Empty string")
    } else {
        println("Either not empty or null")
    }
}
Common Mistakes
  1. Using . instead of ?. on a nullable receiver, which the compiler rejects outright.
  2. Chaining several ?. calls but forgetting the entire chain short-circuits to null the moment any link is null.
  3. Assuming ?. throws an exception on null; it never throws, it simply evaluates to null instead.
Chapter Summary
  • ?. calls a member only if the receiver is not null; otherwise the whole expression evaluates to null.
  • Chained safe calls like a?.b?.c short-circuit to null as soon as any link in the chain is null.
  • ?. never throws an exception -- it is the safe alternative to a plain . on a nullable type.
  • The result of a safe call is always a nullable type, since it might be null.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.