Elvis Operator
In this page:
Providing a Default Value
The Elvis operator ?: returns its left operand if that is not null, or falls back to the right operand otherwise, giving a concise way to supply a default.
Example: Providing a Default Value
fun main() {
val nickname: String? = null
val displayName = nickname ?: "Anonymous"
println("Display name: $displayName")
}
Login to try C/C++/Java/PHP code in the editor
Combining with Safe Calls
?: pairs naturally with ?., letting you write value?.property ?: default to safely reach into a nullable chain and fall back cleanly if anything along the way is null.
Example: Combining with Safe Calls
data class User(val name: String?)
fun main() {
val user: User? = User(null)
val name = user?.name ?: "Unknown"
println("Name: $name")
}
Login to try C/C++/Java/PHP code in the editor
Throwing on Null with Elvis
Because the right side of ?: can be any expression, including throw, it is a common idiom to fail fast with a clear exception when a value that should never be null turns out to be.
Example: Throwing on Null with Elvis
fun requireName(name: String?): String {
return name ?: throw IllegalArgumentException("Name must not be null")
}
fun main() {
println(requireName("Kotlin"))
}
Login to try C/C++/Java/PHP code in the editor
Lazy Evaluation of the Right Side
The expression after ?: is only evaluated if the left side is null, so an expensive computation or a function call placed there does not run unnecessarily.
Note: Notice "Computing default..." never prints, since value was not null.
Example: Lazy Evaluation of the Right Side
fun computeExpensiveDefault(): String {
println("Computing default...")
return "computed"
}
fun main() {
val value: String? = "already set"
val result = value ?: computeExpensiveDefault()
println("Result: $result")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the Elvis operator's right-hand side is only evaluated when the left side is
null, and relying on it to run unconditionally. - Using
if/elseverbosely for a simple default-value case where?:would be far shorter and clearer. - Chaining
?:with athrowand not realizing this is a common, idiomatic way to fail fast on unexpected nulls.
a ?: bevaluates toaifais notnull, otherwise it evaluates tob.- The right-hand side of
?:is only evaluated when needed (it is lazy), so it can safely contain a function call or athrow. - The Elvis operator is often combined with a safe call, like
user?.name ?: "Unknown". ?:can be used to provide a default value or to fail fast with athrow/returnwhen a value is unexpectedlynull.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: