How to Use Safe Call Operator in Kotlin for Null Safety
In Kotlin, use the
?. safe call operator to access a property or method of an object only if it is not null. This prevents null pointer exceptions by returning null instead of throwing an error when the object is null.Syntax
The safe call operator ?. is placed between a nullable object and the property or method you want to access. If the object is null, the whole expression returns null instead of causing an error.
object?.property- safely access a propertyobject?.method()- safely call a method
kotlin
val name: String? = null
val length = name?.lengthOutput
length is null
Example
This example shows how to safely get the length of a nullable string using the safe call operator. If the string is null, the length will also be null without causing an error.
kotlin
fun main() {
val name: String? = null
val length = name?.length
println("Length: $length")
val anotherName: String? = "Kotlin"
val anotherLength = anotherName?.length
println("Length: $anotherLength")
}Output
Length: null
Length: 6
Common Pitfalls
One common mistake is to forget that the result of a safe call is nullable, so you must handle the null case. Also, using ?. on a non-nullable type is unnecessary. Avoid chaining safe calls without handling nulls, which can lead to unexpected null results.
kotlin
fun main() {
val name: String? = null
// Wrong: assuming length is non-null
// val length: Int = name?.length // Error: Type mismatch
// Right: declare length as nullable Int?
val length: Int? = name?.length
println(length) // prints null
}Output
null
Quick Reference
Use this quick guide to remember how the safe call operator works:
| Expression | Meaning | Result if object is null |
|---|---|---|
| object?.property | Access property if object not null | null |
| object?.method() | Call method if object not null | null |
| object?.property?.method() | Chain safe calls | null if any part is null |
| object!!.property | Force access, throws if null | Throws NullPointerException |
Key Takeaways
Use
?. to safely access properties or methods on nullable objects without errors.The result of a safe call is always nullable; handle null cases properly.
Avoid unnecessary safe calls on non-nullable types.
Chaining safe calls returns null if any part is null, preventing exceptions.
Use
!! only when you are sure the object is not null to avoid crashes.