Elvis Operator
In this page:
val result = nullable ?: defaultValue
val result = obj?.property ?: defaultValue
val result = nullable ?: throw SomeException("message")
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
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `nickname` (a `String?`), set to `null`
val nickname: String? = null
// Declare a read-only variable `displayName`, set to `nickname ?: "Anonymous"`
val displayName = nickname ?: "Anonymous"
// Print "Display name: $displayName" to the console, with a trailing newline
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
// Define a data class `User`
data class User(val name: String?)
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `user` (a `User?`), set to `User(null)`
val user: User? = User(null)
// Declare a read-only variable `name`, set to `user?.name ?: "Unknown"`
val name = user?.name ?: "Unknown"
// Print "Name: $name" to the console, with a trailing newline
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
// Define the function `requireName` taking `name` and returning a String
fun requireName(name: String?): String {
// Return `name ?: throw IllegalArgumentException("Name must not be null")` from this function
return name ?: throw IllegalArgumentException("Name must not be null")
}
// Entry point: execution of the program starts here
fun main() {
// Print `requireName("Kotlin")` to the console, with a trailing newline
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.
value was not null.Example: Lazy Evaluation of the Right Side
// Define the function `computeExpensiveDefault` with no parameters and returning a String
fun computeExpensiveDefault(): String {
// Print "Computing default..." to the console, with a trailing newline
println("Computing default...")
// Return `"computed"` from this function
return "computed"
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `value` (a `String?`), set to `"already set"`
val value: String? = "already set"
// Declare a read-only variable `result`, set to `value ?: computeExpensiveDefault()`
val result = value ?: computeExpensiveDefault()
// Print "Result: $result" to the console, with a trailing newline
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: