Kotlin Safe Calls
A safe call asks a value only when there is a value to ask. A safe call on nothing gives null instead of stopping the program.
A safe call on null
The name holds null. The safe call gives null and the program keeps running.
fun main() {
val name: String? = null
println(name?.length)
}A safe call on a real value
The name holds a word. The safe call gives the length of that word.
fun main() {
val name: String? = "Ana"
println(name?.length)
}The !! call on a present value
The name holds a word. The !! call asks for its length directly.
fun main() {
val name: String? = "Bo"
println(name!!.length)
}A plain call on a nullable value
This code tries a plain dot call on a String?. The compiler refuses the program.
fun main() {
val name: String? = null
println(name.length)
}Example
fun main() {
val name: String? = null
val size = name?.length
if (size == null) {
println("No name")
} else {
println(size)
}
val city: String? = "Oslo"
println(city?.length)
}Key points
- Safe call: the ?. written between a value and the part asked for.
- Use ?. to ask a nullable value for its length safely.
- A safe call on null gives null.
- Non-null asserted call: the !! written after a value.
- Use !! only when a value is sure to be present.
In this example, name holds null, so its safe call gives null. The if test sees null and prints No name. The city holds Oslo, so its safe call prints 4.
Note
!! on null stops the program with an error.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does name?.length give when name holds null?