Skip to main content

Kotlin: safe call operator ?.

?.

What does the safe call operator do?

  • Symbol for safe call operator is ?.
  • It safely calls function or accesses property of a nullable object
  • Returns null in case the object has null value, else calls the function or accesses property.
  • Safe call operator can be chained and returns null if any of the object in chain.
var msg: String?
msg = null
println(msg?.length) // prints "null"
// here msg?. returns null since msg is null, 
// instead of accessing the .length property
Chaining safe call operator
println(foo?.bar?.baz?.someProp)
This chain would return null if either of foo, bar or baz have null value but won't check someProp for null value!

Comments