🐦 Kotlin Beginner

What is the safe call operator (?.) in Kotlin?

Answer

The safe call operator ?. allows you to call a method or access a property on a nullable object without risking a NullPointerException. If the object is null, the expression returns null instead of throwing an exception. For example, name?.length returns the string length if name is not null, or null if it is. Safe calls can be chained: user?.address?.city — if any value in the chain is null, the entire expression returns null. This is one of Kotlin's most used null-safety features.