Kotlin Elvis Operator
The Elvis operator gives a fallback value when the value on its left is null. The fallback keeps a program working with a plain value instead of null.
A fallback for a missing length
The name holds null. The safe call gives null, so the fallback 0 is used.
fun main() {
val name: String? = null
println(name?.length ?: 0)
}No fallback needed for a real length
The name holds a word. Its length is used and the fallback is ignored.
fun main() {
val name: String? = "Ana"
println(name?.length ?: 0)
}A fallback word on its own
The nickname holds null. Printing the Elvis expression shows the fallback word.
fun main() {
val nickname: String? = null
println(nickname ?: "Guest")
}An Elvis value saved in a val
The size takes the fallback 0. A later print adds 10 to that saved value.
fun main() {
val name: String? = null
val size = name?.length ?: 0
println(size + 10)
}Example
fun main() {
val nickname: String? = null
val displayName = nickname ?: "Guest"
println("Hello, $displayName")
val name: String? = "Cy"
val size = name?.length ?: 0
println(size)
}Key points
- Elvis operator: the ?: written between a value and its fallback.
- Use ?: to supply a fallback when the left side is null.
- A non-null left side is used as it is.
- A fallback can be a number or a word.
In this example, the nickname holds null, so displayName takes the fallback Guest. The greeting prints that fallback. The name holds Cy, so size takes its real length 2.
Note
?: works with a safe call, as in name?.length ?: 0.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
When name holds null, what value does name?.length ?: 0 give?