In Kotlin, the safe call operator ?. lets you access a property or call a function only if the value is not null.
If the value is null, the expression simply returns null instead of throwing a NullPointerException.
val name: String? = null
val length = name?.length
println(length) // null
Here, name is nullable because its type is String?. Since name is null, name?.length does not try to access .length; it returns null.
Basic syntax
nullableValue?.property
nullableValue?.function()
Example:
val user: User? = getUser()
val email = user?.email
If user is not null, email gets user.email.
If user is null, email becomes null.
Chaining safe calls
You can chain multiple safe calls together:
val city = user?.address?.city
This means:
- if
userisnull, returnnull - otherwise check
address - if
addressisnull, returnnull - otherwise return
city
Using ?. with a default value
Often, you combine ?. with the Elvis operator ?::
val length = name?.length ?: 0
This means:
- if
nameis notnull, usename.length - if
nameisnull, use0
Using ?.let
Use ?.let when you want to run code only when a value is not null:
val name: String? = "Kotlin"
name?.let {
println("Name is $it")
println("Length is ${it.length}")
}
The block runs only if name is not null.
Safe call on assignment
Safe calls can also be used on the left side of an assignment:
person?.address?.city = "Paris"
If person or address is null, the assignment is skipped.
Summary
val result = nullableValue?.someProperty
Use ?. when:
- a value might be
null - you want to avoid
NullPointerException - returning
nullis acceptable when the receiver isnull
Common pattern:
val result = nullableValue?.someProperty ?: defaultValue
