0
0
Kotlinprogramming~5 mins

Safe call operator (?.) in Kotlin

Choose your learning style9 modes available
Introduction

The safe call operator (?.) helps you avoid errors when working with values that might be null. It lets you safely access properties or call functions without crashing your program.

When you want to access a property of an object that might be null.
When calling a function on an object that could be null and you want to avoid errors.
When you want to chain calls but some parts might be missing (null).
When you want to return null instead of crashing if a value is missing.
Syntax
Kotlin
val result = someObject?.propertyOrFunction()

The operator ?. checks if someObject is not null before accessing the property or calling the function.

If someObject is null, the whole expression returns null instead of causing an error.

Examples
Access name only if person is not null.
Kotlin
val name: String? = person?.name
Get the length of text if it is not null, otherwise length will be null.
Kotlin
val length = text?.length
Get the first character of text safely if text is not null.
Kotlin
val firstChar = text?.get(0)
Sample Program

This program creates a Person object and safely gets the length of the name using the safe call operator. It also shows what happens when the person is null.

Kotlin
fun main() {
    val person: Person? = Person("Alice")
    val nameLength = person?.name?.length
    println("Name length: $nameLength")

    val noPerson: Person? = null
    val noNameLength = noPerson?.name?.length
    println("Name length when person is null: $noNameLength")
}

data class Person(val name: String)
OutputSuccess
Important Notes

The safe call operator helps prevent NullPointerException errors.

You can chain multiple safe calls like obj?.a?.b?.c.

If you want to provide a default value when null, combine with the Elvis operator: obj?.property ?: defaultValue.

Summary

The safe call operator (?.) lets you access properties or call functions only if the object is not null.

If the object is null, the expression returns null instead of crashing.

This makes your code safer and easier to read when dealing with nullable values.