Elvis Operator (?:) (Kotlin)
The Elvis operator ?: returns its left side if it's not null, otherwise the right side. It's Kotlin's concise way to supply a default value for a nullable expression.
Kotlin
Written a ?: b, it evaluates to a when a is non-null and to b otherwise. The name comes from the operator looking like Elvis Presley's hair and eyes when rotated. It's the idiomatic way to replace null with a fallback.
It pairs naturally with the safe-call operator: name?.length ?: 0 reads 'the length if name is non-null, else 0'. The right side can also be a throw or return, making ?: a clean early-exit guard: val id = user.id ?: return.
Compared to a full if/else or the ternary other languages have (which Kotlin lacks), the Elvis operator is shorter and signals intent — 'use this, or this default' — clearly.
Syntax
val result = nullableValue ?: defaultValueExamples
Kotlin
fun displayName(name: String?): String {
return name ?: "Anonymous"
}
println(displayName("Sam"))
println(displayName(null))Output:
Sam
Anonymous