skip to content

Elvis Operator ?:

?: supplies a fallback when the left side is null, and because the right side can be throw or return it doubles as an early-exit guard. The 'value ?: return' idiom is one of the most idiomatic lines in Kotlin.

part ofKotlinoverview, primer and where to startread it →
on this pageshow

questions

5

What does the Elvis operator ?: do in Kotlin, and what is a typical example of using it?

level: juniorimportance: must knowfreq 80%

answer

  1. left if non-null else right
  2. ?: = null-coalescing
  3. right side short-circuits
  4. pairs with ?.
  5. result is non-null if right is non-null

basics

~10 s

The Elvis operator ?: gives a fallback value when the left side is null. You write a ?: b: if a is not null you get a, otherwise you get b.

solid answer

~40 s

The Elvis operator `a ?: b` evaluates to `a` when `a` is non-null, and to `b` when `a` is null. It is the idiomatic way to supply a default for a nullable expression, replacing verbose `if (a != null) a else b`. The right side is only evaluated when the left is null (short-circuit). The result type is the common supertype of both branches; if the left side is `String?` and the right is a non-null `String`, the overall expression is `String` (smart non-null). It pairs naturally with safe calls, e.g. `name?.trim() ?: "unknown"`. The name comes from the `?:` glyph resembling Elvis Presley's hair and eyes when read sideways.

code

kotlin · 7 lines
kotlin
fun greet(name: String?): String {
    val safeName = name ?: "guest"
    return "Hello, $safeName"
}

println(greet("Ada"))  // Hello, Ada
println(greet(null))   // Hello, guest

go deeper

for a junior

Knows a ?: b returns a when non-null else b, and can write a simple default.

for a middle

Explains short-circuit evaluation and that the result becomes non-null when the right side is non-null.

for a senior

Discusses pairing with ?. chains, side-effect timing on the right, and resulting type inference.

for a principal

Frames Elvis within a broader null-handling policy (defaults vs. fail-fast) and readability/cost trade-offs.

## What the Elvis operator is The **Elvis operator** is written `?:` and has the form `left ?: right`. It is Kotlin's null-coalescing operator: it returns the **left** operand if that operand is **not null**, otherwise it returns the **right** operand. - `null` here means the Kotlin absence-of-value: a variable of a **nullable type** (a type written with a trailing `?`, e.g. `String?`) may hold `null`. - The operator lets you turn a nullable value into a usable default value in one expression. ```kotlin val name: String? = readName() val display: String = name ?: "unknown" // "unknown" when name is null ``` ## Short-circuit evaluation The right side is **only evaluated when the left side is null**. So in `cache ?: computeExpensiveDefault()`, `computeExpensiveDefault()` does not run when `cache` is non-null. This matters when the right side has side effects or is costly. ## Result type The type of `a ?: b` is the **least common supertype** of the two sides. A key consequence: if `a: String?` and `b: String` (non-null), then `a ?: b` has type `String` — non-null — because once you reach this expression either the non-null `a` or the non-null `b` is produced. ## Equivalent without Elvis ```kotlin val display = if (name != null) name else "unknown" ``` The Elvis form is shorter and avoids repeating the expression. ## Common pairing with safe call ?. The **safe call** `?.` returns `null` if its receiver is null. Combined with Elvis you get a default for a whole chain: ```kotlin val len = text?.length ?: 0 ``` Here `text?.length` is `Int?`; Elvis turns it into a plain `Int` defaulting to `0`.

  • Is the right side always evaluated?
    No. It is evaluated only when the left side is null (short-circuit), so side effects on the right run only in the null case.
  • What is the type of `x ?: 0` when `x` is `Int?`?
    `Int` (non-null), because both possible results are non-null.

Like a backup generator: use mains power if it's on, otherwise switch to the generator.

saying these in an interview costs you the question

  • Saying ?: checks for false/zero rather than null
  • Claiming the right side always runs
  • Confusing ?: with the safe call ?.
  • Thinking it works on non-nullable types meaningfully

context

open as a page

How is the Elvis operator used with return and throw for early-exit null guards, and why does it work?

level: middleimportance: must knowfreq 72%

basics

~10 s

You can put return or throw on the right side of ?:. If the left is null, the function returns early or throws; otherwise execution continues with the non-null value.

open as a page

What is the precedence and associativity of the Elvis operator, and how does `a ?: b ?: c` evaluate?

level: middleimportance: should knowfreq 45%

basics

~20 s

Elvis is right-associative, so a ?: b ?: c means a ?: (b ?: c) — it falls through to the first non-null value left to right. It has low precedence, so combine with other operators carefully using parentheses.

open as a page

Compare the Elvis operator with alternatives like ?.let, requireNotNull/checkNotNull, and !! for handling nullable values. When would you choose each?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Use ?: to supply a default or to exit early on null. Use requireNotNull/checkNotNull to assert a value must exist with a clear message. Avoid !!, which throws an unhelpful NPE. Use ?.let to run code only when non-null.

open as a page

What are the evaluation semantics and pitfalls of the Elvis operator's right-hand side — side effects, double evaluation, and use in expressions returning Unit?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

The right side of ?: runs only when the left is null, so put side effects there carefully. The left side is evaluated once. Watch out when the right side returns Unit or has effects you didn't intend.

open as a page