Elvis Operator is a binary operator that returns the left operand if it is not null, and the right operand otherwise. It is written as ?: in Kotlin, Groovy, and some other languages. According to Kotlin Language Documentation, 2024, the operator is part of the language's null safety system and allows conditional constructs to be shortened to a single line without loss of readability. Unlike a full if-else expression, the Elvis Operator evaluates the right side only when the left side is null, providing a performance advantage when using expensive default expressions.
Key Takeaways
Elvis Operator is a binary operator named after Elvis Presley's hairstyle. The ?: symbol visually resembles the singer's face from the side: the question mark is the eye and sideburn, the colon is the mouth. The operator takes two operands: if the first is not null — it is returned, otherwise the second is returned. This allows a full if-else construct to be replaced with a single short expression.
The name “Elvis Operator” became established in the Kotlin and Groovy communities and later spread to Xtend and other JVM languages. In Swift and Dart, the analogous construct is called the nil-coalescing operator, but it is functionally identical. The visual association with Elvis Presley helped the operator become one of the most recognizable symbols in modern programming language syntax.
The Elvis Operator is part of the null safety system that prevents NullPointerException (NPE). According to a 2023 JetBrains study, NPE accounts for 28% of all exceptions in production JVM code. Using the Elvis Operator completely eliminates NPE at the assignment point, guaranteeing a default value. In combination with the safe call operator ?., a reliable chain is created without a single if block.
In Kotlin, the Elvis Operator is written as ?: between two expressions. If the left expression is not null — the result equals the left expression, otherwise the right expression is evaluated. The right expression is evaluated lazily — only when the left operand is null, which matters for performance when using expensive computations or API calls.
val name: String? = getUserName()
val displayName = name ?: "Guest"
fun getLength(str: String?): Int {
return str?.length ?: 0
}
val config: Config? = loadConfig()
val timeout = config?.timeout ?: 30
println("Timeout: $timeout")
// Elvis with throw for required parameters
val requiredId = nullableId ?: throw IllegalArgumentException("ID is required")
// Elvis with return for early exit
fun process(data: String?): Result {
val safe = data ?: return Result.failure("No data")
return processInternal(safe)
}
Combining with let is a common pattern in Kotlin, where the Elvis Operator provides a default value, and let performs an action on the non-null result. This approach replaces entire if-else blocks with a single call chain without loss of readability. The Elvis Operator can also be used with throw to forcibly abort when a required parameter is missing — this is an idiomatic way to validate input data.
A common pattern in Kotlin is Elvis + return. If the value is null, the function immediately returns a result or throws an exception. The Elvis with return idiom is often used in data transformation functions: val processed = rawData ?: return defaultValue. This is more compact than Swift's guard let and does not increase code nesting.
Elvis Operator is shorter than if-else and does not require repeating the variable. Compare: val x = a ?: b versus val x = if (a != null) a else b. With complex expressions, code reduction reaches 60%, while the semantics are completely identical — the compiler can generate the same bytecode for both variants.
| Criterion | Elvis Operator | if-else |
|---|---|---|
| Length | 1 line, 5–10 chars | 3 lines, 15–30 chars |
| Expression repetition | No | Yes (a != null) ? a : b |
| Lazy right side | Yes | Yes (elvis is shorter) |
| Side effects | Only on the right side | In both branches |
| Readability | High for simple cases | Better for complex logic |
The Elvis Operator is optimal for assigning default values, chaining function calls with safe access, and logging missing values. Idiomatic Kotlin patterns recommend it as a replacement for if-else for simple null checks in expressions. Combined with ?., it produces compact chains without temporary variables.
if-else remains preferable for multiple conditions, when side effects need to be executed, or when both operands are complex code blocks with several operations. The Elvis Operator does not support nested blocks — only single expressions for each operand. If the right side calls a function with side effects, if-else readability is higher.
Groovy uses exactly the same ?: syntax as Kotlin, since both languages run on the JVM and share the null-safety philosophy. The operator appeared earlier in Groovy — it has been in the language since version 1.8, released in 2011. Groovy also supports Elvis assignment: x ?= value (assign only if x is null).
def name = getUserName()
def display = name ?: "Guest"
def map = ["key": "value"]
def result = map?.get("missing") ?: "default"
println(result)
// Elvis assignment in Groovy
def config = null
config ?= "defaultConfig"
assert config == "defaultConfig"
In Swift, the equivalent is called the nil-coalescing operator and is written as ??. In Dart, the same ?? syntax is used. The difference is that Swift and Dart require matching operand types, while Kotlin allows different types with automatic conversion to a common supertype. In TypeScript, the ?? operator (nullish coalescing) appeared in version 3.7 and works only with null and undefined, unlike || which filters all falsy values. In PHP, the ?? operator appeared in version 7.0, in C# — ?? since version 6.0.
The most common mistake is confusing the Elvis Operator ?: with the safe call operator ?. In Kotlin, ?. calls a method or property only if the object is not null, while ?: returns a default value when null. They are combined sequentially, but each performs its own function. The confusion arises among beginners who try to use ?: without ?. before it.
The right side of Elvis is evaluated lazily, but if it contains a function call with side effects, it can lead to unexpected behavior. Developers sometimes put expensive computations or logging on the right side, which is not executed when the value is non-null. It is important to remember that the right side is an expression that is evaluated only when necessary.
Multiple Elvis operators in a row can make code harder to read. For example, a ?: b ?: c ?: d is evaluated left to right, returning the first non-null. Grouping with parentheses or extracting logic into a separate function improves readability and debugging. If the chain is longer than 3 elements, a when expression or helper function should be used.
Beginner developers sometimes try to use the Elvis Operator to check boolean values: val x = flag ?: false. This only works if flag can be null. For boolean conditions without null, a regular if-else or ternary operator is needed — Kotlin does not have a ternary operator, but it is replaced by the if-else expression: val x = if (flag) a else b.
Frequently Asked Questions
Elvis Operator only checks for null, while the ternary operator accepts any boolean condition. Kotlin does not have a ternary operator — it is replaced by the if-else expression. Elvis solves one specific task: a default value when null, whereas the ternary operator covers all conditional expressions.
Yes, the right side can be a function call: val x = a ?: calculateDefault(). The function is evaluated only when a is null thanks to lazy evaluation. This allows expensive computations, API calls, or database queries to be used without performance loss when a value is present.
Java does not have a direct Elvis Operator. Starting from Java 8, Optional.ofNullable(value).orElse(default) can be used. Java 14+ introduced switch expressions, but a full ?: is absent. Kotlin and Groovy provide it as a built-in syntactic construct of the language.
The typical pattern is a safe call ?. followed by Elvis. Example: user?.address?.city ?: “Unknown”. If any element in the chain is null — the default value is returned. This is a compact replacement for nested if checks, reducing code by 3–5 times compared to the traditional approach.
Elvis Operator is a syntactic construct at the language level, while orElse is a method of Optional in Java. Elvis is lazy (the right side is evaluated only when null), while orElse always evaluates its argument. For a lazy variant in Java, there is orElseGet, which accepts a Supplier. Elvis is shorter and does not require creating an Optional.
Summary
We will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also