Safe Call Operator (?.) (Kotlin)

The safe-call operator ?. calls a method or accesses a property only if the receiver is non-null; if it's null, the whole expression evaluates to null instead of throwing a NullPointerException.

Kotlin

Writing person?.name returns person.name when person is non-null and null when it is null — no crash. You can chain it: order?.customer?.address?.city short-circuits to null the moment any link is null.

Combine it with the Elvis operator to provide a fallback (name?.length ?: 0) or with .let to run a block only when the value is present (name?.let { println(it) }). The expression's result type becomes nullable, which the compiler tracks.

Safe call is the everyday tool of Kotlin null handling. Reach for it instead of manual if (x != null) checks, and avoid the !! operator unless you can guarantee non-null.

Syntax

val length = text?.length   // Int? — null if text is null

Examples

Kotlin

val text: String? = null
println(text?.uppercase())
println("hi"?.uppercase())

Output:

null
HI

Learn it in a lesson

See also

Back to the Dictionary