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.
Safe call operator (?.) in 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.
name only if person is not null.val name: String? = person?.name
text if it is not null, otherwise length will be null.val length = text?.lengthtext safely if text is not null.val firstChar = text?.get(0)
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.
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)
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.
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.