← Back to Kotlin Course | Chapter 5: Null Safety | Lesson 3 of 6

Elvis Operator

The Elvis operator lets you say 'use this value, but if it's empty, use this backup value instead', all in one short line.

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

markup
fun main() {
    val nickname: String? = null
    val displayName = nickname ?: "Anonymous"
    println("Display name: $displayName")
}

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

markup
data class User(val name: String?)

fun main() {
    val user: User? = User(null)
    val name = user?.name ?: "Unknown"
    println("Name: $name")
}

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

markup
fun requireName(name: String?): String {
    return name ?: throw IllegalArgumentException("Name must not be null")
}

fun main() {
    println(requireName("Kotlin"))
}

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

markup
fun computeExpensiveDefault(): String {
    println("Computing default...")
    return "computed"
}

fun main() {
    val value: String? = "already set"
    val result = value ?: computeExpensiveDefault()
    println("Result: $result")
}
Common Mistakes
  1. Forgetting the Elvis operator's right-hand side is only evaluated when the left side is null, and relying on it to run unconditionally.
  2. Using if/else verbosely for a simple default-value case where ?: would be far shorter and clearer.
  3. Chaining ?: with a throw and not realizing this is a common, idiomatic way to fail fast on unexpected nulls.
Chapter Summary
  • a ?: b evaluates to a if a is not null, otherwise it evaluates to b.
  • The right-hand side of ?: is only evaluated when needed (it is lazy), so it can safely contain a function call or a throw.
  • 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 a throw/return when a value is unexpectedly null.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.