Safe Call Operator
In this page:
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
fun main() {
val name: String? = "Kotlin"
val nullName: String? = null
println(name?.length)
println(nullName?.length)
}
Login to try C/C++/Java/PHP code in the editor
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val input: String? = " hello "
val trimmed = input?.trim()
println("Trimmed: $trimmed")
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val text: String? = null
if (text?.length == 0) {
println("Empty string")
} else {
println("Either not empty or null")
}
}
Login to try C/C++/Java/PHP code in the editor
- Using
.instead of?.on a nullable receiver, which the compiler rejects outright. - Chaining several
?.calls but forgetting the entire chain short-circuits tonullthe moment any link isnull. - Assuming
?.throws an exception onnull; it never throws, it simply evaluates tonullinstead.
?.calls a member only if the receiver is notnull; otherwise the whole expression evaluates tonull.- Chained safe calls like
a?.b?.cshort-circuit tonullas soon as any link in the chain isnull. ?.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: