Fact-checked by Grok 2 weeks ago

Elvis operator

The Elvis operator, denoted by the symbol ?:, is a binary featured in various programming languages that evaluates its left and returns it if the operand is not (in null-safe languages) or truthy (according to the language's rules in other languages); otherwise, it returns the right operand. This construct acts as a for the (condition ? trueExpression : falseExpression) in scenarios where the condition and true expression are identical, such as providing a default value for potentially null references, thereby minimizing code repetition and enhancing readability. For example, in , the expression user.name ?: 'Anonymous' evaluates to the user's name if available, or 'Anonymous' as a fallback. The operator derives its informal name from American singer Elvis Presley, as the ?: symbol, when viewed sideways (rotated 90 degrees clockwise), resembles his iconic pompadour hairstyle or a stylized winking emoticon evoking his image. First popularized in the Groovy programming language around 2007, it quickly influenced other dynamic and statically typed languages seeking concise null-handling syntax. In , the Elvis operator integrates with the language's flexible "Groovy truth" semantics, where falsy values include null, empty strings, and zero, making it ideal for against unexpected nulls. Kotlin employs it prominently within its robust null safety system, often chained with the safe call operator (?.) to avoid exceptions, as in val length = text?.length ?: 0. In PHP, introduced as the short ternary in version 5.3 (2009), it functions similarly by omitting the explicit condition when evaluating the left operand for truthiness: $name ?: 'Guest'. The operator's adoption underscores a broader trend in modern languages toward succinct, safe navigation of optional values, though its exact behavior varies slightly by implementation—such as strict null checks in Kotlin versus broader falsiness in .

Fundamentals

Definition

The Elvis operator, denoted as ?:, is a binary in certain programming languages that evaluates its left and returns that operand if it is truthy—meaning non-null and non-falsy according to the language's semantics—otherwise returning the right operand. This operator serves as a for conditional expressions where the condition is implicitly the truthiness of the left operand itself. In conceptual terms, the Elvis operator can be understood through as result = (left is truthy) ? left : right, effectively omitting the explicit condition from a full while preserving the same logical outcome for or falsy checks. It thus streamlines the assignment of default values or the handling of potentially absent data, reducing that would otherwise require verbose if-else statements or explicit conditions. This operator is distinct from the standard ternary operator (condition ? trueValue : falseValue) primarily by integrating the left operand as both the condition and the true branch, focusing on null-safety and defaulting scenarios. The Elvis operator first appeared in version 1.5, released in December 2007.

Purpose

The Elvis operator primarily simplifies null-safe default value assignments by providing a for expressions that evaluate to a truthy or non-null value, otherwise falling back to a specified default. This construct reduces the boilerplate inherent in traditional conditional statements, such as if-else blocks, allowing developers to express logic more concisely without compromising code clarity or intent. Among its key benefits, the enhances readability by streamlining verbose conditional logic into a single, intuitive expression, thereby minimizing cognitive overhead for maintainers. It also prevents exceptions in object chaining operations, where intermediate values might be null, and supports functional-style programming paradigms in object-oriented languages by promoting immutable defaults and safer data flows. The operator addresses common pain points in , including the handling of optional values and the provision of fallbacks in , particularly emphasizing error prevention in dynamic languages where is less enforced. In scenarios involving truthy checks, it reduces code verbosity and duplication, lowering the risk of refactoring errors by eliminating the need to repeat evaluated expressions.

Syntax

Basic Syntax

The Elvis operator is denoted by the notation expression1 ?: expression2, where it evaluates expression1 and returns its value if truthy (according to the language's rules), otherwise returning expression2. This binary operator serves as a for providing a default value, mirroring the structure of a conditional but omitting the explicit repetition of the condition. In terms of rules, the Elvis operator has a precedence level higher than operators but lower than logical AND (&&) and OR (||) operators, ensuring that logical operations bind more tightly in mixed expressions. It is right-associative, meaning that in chained expressions like a ?: b ?: c, the operator groups as a ?: (b ?: c). The operator must appear within expression contexts, such as variable assignments, return s, or other positions where a value is expected, and it cannot standalone as a . Evaluation proceeds by first assessing expression1 for or (depending on the language); if it qualifies, expression2 is not evaluated due to short-circuiting behavior, which optimizes performance by avoiding unnecessary computations. The exact criteria for when expression1 is considered valid vary by language; see the Variants subsection for details. The return type is inferred from the selected , typically the type of the non-null or truthy expression, allowing for flexible type handling in both dynamic and static contexts.

Variants

In some programming languages, the Elvis operator can be combined with the safe navigation operator to handle chained null checks in a single expression, such as accessing nested while providing a default if any part of the chain is . This variant extends the basic by integrating null-safe access before applying the default value logic. Specific implementations of the Elvis operator vary in their evaluation criteria: the truthy/falsy variant treats the left as falsy (including , false, zero, or empty collections) and returns the right only if the left is falsy, as seen in . In contrast, the null-specific form checks exclusively for values on the left , ignoring other falsy states, which is the approach in Kotlin. Additionally, assignment forms exist, such as the Elvis assignment operator introduced in 3.0, which assigns a default value to a only if it is currently . Chaining multiple Elvis operators enables cascading defaults, where the expression evaluates from left to right and selects the first non-null (or non-falsy, depending on the variant) , providing a concise way to specify hierarchical fallback values. In typed languages like Kotlin, the Elvis operator integrates with generics and nullable types, where the resulting type is the least upper bound of the non-nullable left-hand side type and the right-hand side type, enhancing null safety in generic contexts.

Examples

Null Coalescing

The Elvis operator serves as a null coalescing mechanism by evaluating the left-hand expression and returning its value if it is not null, otherwise substituting the right-hand expression as a default. This functionality streamlines code by avoiding verbose conditional checks for values, promoting readability in scenarios where defaults are essential. A representative example in pseudocode illustrates this behavior:
pseudocode
name = userInput ?: 'Anonymous'
Here, if userInput evaluates to a non-null value, name is assigned that value; otherwise, it defaults to the string 'Anonymous'. This demonstrates the operator's role in providing a fallback, akin to a shorthand for name = userInput != null ? userInput : 'Anonymous'. In (version 5.3 and later), it checks for falsy values:
php
$name = $userInput ?: 'Anonymous';
If $userInput is truthy, $name is set to it; otherwise, to 'Anonymous'. Falsy includes , empty strings, false, or zero. The evaluation proceeds step-by-step: the left expression is assessed first for nullity (or falsiness in some implementations, encompassing , empty strings, false, or zero); if deemed valid, it is returned immediately, and the right expression is not evaluated, ensuring lazy execution and avoiding potential side effects from unnecessary computations. The output type is typically the common supertype of both operands, preserving without implicit conversions unless specified. No inherent side effects arise from the operator itself, though the expressions involved may introduce them if not designed carefully. In response handling, the Elvis operator prevents runtime errors by assigning predefined defaults to optional fields, such as setting a user's profile image to a if the server omits the field: profileImage = apiResponse.imageUrl ?: defaultPlaceholder. This approach ensures robust without exceptions. The operator finds common application in web development for form validation, where user-submitted fields default to safe values if empty or null, and for configuration loading, substituting environment variables with hardcoded fallbacks to maintain application stability.

Safe Navigation

The Elvis operator plays a crucial role in facilitating safe navigation through object hierarchies by integrating with the safe call operator (?. ) in languages like and Kotlin, allowing developers to access properties or invoke methods on potentially null objects without triggering NullPointerExceptions. This combination ensures that if any intermediate object in the chain is null, the evaluation short-circuits and returns null, which the Elvis operator then replaces with a specified default value. For instance, in , the expression fullName = user?.name ?: 'Unknown' safely retrieves the name property from a user object only if user is non-null; otherwise, it defaults to 'Unknown', preventing errors during property access. Note that does not have a safe call operator, so this integration is not applicable there. Step-by-step, the process begins with the safe navigation operator (?.), which attempts property access or method invocation but immediately yields upon encountering a , thereby avoiding exceptions. The Elvis operator (?:) then evaluates this result: if it is non-null, the value is used; if , the right-hand side provides the fallback. This mechanism is particularly valuable in object-oriented contexts, extending null coalescing to chained operations and enabling robust handling of incomplete data structures. A common scenario for this feature arises in data processing tasks, such as traversing object graphs during parsing or executing queries, where nested objects like user.address?.street ?: 'No Address' might contain nulls due to incomplete datasets. By short-circuiting on nulls, it streamlines code for scenarios involving user profiles, database records, or responses, reducing boilerplate null checks. This integration promotes the creation of fluent interfaces, where can proceed without interspersed explicit null guards, thereby enhancing code readability and maintainability in large-scale applications.

History

Origin

The Elvis operator was first implemented in version 1.5, released on December 7, 2007, as a shorthand for the ternary operator specifically tailored for dynamic scripting on the platform. This operator, denoted as ?:, allows for concise assignment of default values when the primary expression evaluates to or false according to Groovy's truth rules, thereby reducing common in Java-like environments. The operator was proposed during the language's maturation phase in mid-2007 under the leadership of project manager Guillaume Laforge. Laforge led the development team in integrating this feature to address the verbosity of explicit null checks and conditional expressions in -influenced syntax, enhancing code readability and maintainability for scripting tasks. The proposal emerged as part of 's broader evolution from a simple Java scripting tool—initially conceived in —to a more expressive supporting advanced features like annotations and generics alongside Java 5 compatibility. This addition aimed to bolster Groovy's utility in domains requiring rapid development, such as frameworks like Grails and systems like , both of which leveraged Groovy's dynamic nature for configuration and scripting. By streamlining null-safe operations, the Elvis operator contributed to Groovy's goal of providing a more fluid alternative to for these use cases, influencing subsequent language designs.

Naming

The Elvis operator derives its name from a visual pun referencing Elvis Presley, as the symbol ?:, when rotated 90 degrees clockwise, resembles the singer's distinctive pompadour hairstyle or a smirking emoticon. This colloquial term was first coined by Apache Groovy developers in the release notes for Groovy 1.5, introduced in December 2007, where the operator was documented as a shorthand for the ternary operator to provide default values. The name rapidly spread through developer blogs, forums, and community discussions, establishing it as a playful yet enduring reference in programming literature. While alternative designations like "null-safe operator" or "default operator" are used in some technical contexts to describe its function, the "Elvis" moniker prevailed owing to its memorable visual association and has since appeared in official documentation for languages such as Kotlin. The adoption of such whimsical naming conventions underscores a broader tradition in the programming community of assigning humorous, appearance-based nicknames to operators, exemplified by the "spaceship operator" (<=>) in and , which evokes a flying craft, or Python's "walrus operator" (:=), reminiscent of the animal's tusks.

Implementations

Groovy

The Elvis operator (?:) was introduced in version 1.5, released in December 2007, as a shorthand for the ternary operator to provide default values when an expression evaluates to false according to Groovy's truth rules. This operator simplifies null and falsy checks, returning the left-hand operand if it is truthy or the right-hand operand otherwise. It supports full chaining with the safe navigation operator (?.), enabling safe property access on potentially null dynamic objects, as in person?.name ?: 'Anonymous', which avoids NullPointerExceptions while providing defaults. Unique to , the Elvis operator adheres to the language's truthiness semantics, treating non-null objects, non-empty collections, and non-zero numbers as true, which extends its utility beyond simple null coalescing to handle empty or zero values intuitively. This integration aligns with Groovy's dynamic nature, allowing the operator to work seamlessly in expressions involving and meta-programming, such as assigning default closure behaviors in runtime-modified classes. The operator aligns with the general Elvis syntax but leverages Groovy's dynamic typing for flexible, runtime-resolved evaluations. In practice, the Elvis operator is widely used in build scripts to establish property defaults, for instance, def appVersion = project.findProperty('appVersion') ?: '1.0.0', ensuring builds proceed with sensible fallbacks when external properties are absent. It also facilitates script automation by handling optional configurations, such as def timeout = config?.timeout ?: 30, promoting robust, concise code in dynamic scripting environments like Jenkins pipelines or custom DSLs. As of Groovy 5.0.0 (released in 2024), enhancements in interoperability continue to extend the Elvis operator's effectiveness with modern Java features, including records and sealed classes, by enabling null-safe defaults in hybrid codebases without additional boilerplate; recent fixes improve compatibility with CompileStatic annotations.

Kotlin

The Elvis operator (?:) was introduced in Kotlin 1.0, released on February 15, 2016, as a core component of the language's null safety system. It evaluates the left-hand expression and returns it if non-null; otherwise, it returns the right-hand expression, with the right side evaluated only when necessary to avoid unnecessary computations. Unlike operators in dynamically typed languages, the Elvis operator in Kotlin is strictly for handling null values and does not treat other falsy values (such as empty strings or zero) as triggers for the fallback, enforcing compile-time . A distinctive feature of the Elvis operator in Kotlin is its integration with the language's nullable , where types are non-nullable by default and marked as nullable with a trailing (e.g., String?). The permits the operator only in contexts involving nullable types, issuing a type mismatch error if applied to a guaranteed non-null expression, which prevents redundant usage. Following the Elvis operator, if the right-hand side provides a non-null value, the performs a smart cast on the result, treating it as non-nullable for subsequent operations within the scope, enhancing without explicit casts. This aligns with Kotlin's annotations for nullability in interoperability, such as mapping Java's @Nullable to Kotlin's nullable types, ensuring seamless handling of legacy code. In practice, the Elvis operator is widely used in development for safe data handling, particularly in data binding where nullable model properties (e.g., from network responses) require defaults to prevent crashes in view rendering. For example:
kotlin
val displayName: [String](/page/String) = user?.name ?: "Anonymous User"
This provides a fallback for null names in layouts or adapters. It also facilitates safe calls in concurrent environments, such as coroutines, by supplying defaults for potentially null results from asynchronous operations, reducing the risk of exceptions in multi-threaded code. As of Kotlin 2.0 (2024) and later versions such as 2.2.20 (October 2025), the Elvis operator benefits from ongoing optimizations in Kotlin Multiplatform projects, ensuring consistent null handling across JVM, , and Native targets with improved compiler performance and stability for shared codebases. This multiplatform support, stable since Kotlin 1.9.20, allows developers to leverage the operator uniformly in cross-platform applications without platform-specific null behavior variations.

PHP

In PHP, the Elvis operator, denoted as ?:, serves as a shorthand for the ternary conditional operator. It was introduced in PHP 5.3.0, released on June 30, 2009, allowing developers to write more concise conditional expressions. The syntax expr1 ?: expr2 evaluates to expr1 if expr1 is truthy—meaning it is not false, null, 0, 0.0, an empty string '', an empty array [], or any other falsy value—otherwise, it returns expr2. Unlike the full ternary operator (expr1 ? expr1 : expr2), the Elvis operator evaluates the left operand only once, reducing redundancy when the true branch reuses the condition. This operator short-circuits similarly to the logical OR (||) operator, meaning the right expr2 is not evaluated if expr1 is truthy, which can improve performance and avoid side effects in the fallback expression. However, it does not suppress notices for undefined variables; attempting to use an undefined variable as expr1 will trigger an E_NOTICE, unlike the ?? introduced in 7.0. For example:
php
$value = $undefinedVar ?: 'default';  // Triggers E_NOTICE for undefined $undefinedVar
This behavior makes the Elvis operator suitable for scenarios where falsy values beyond just null or unset variables should trigger a fallback, but developers must ensure variables are defined to avoid warnings. Common usage patterns in PHP include providing defaults in web forms and configuration handling. In form processing, it sanitizes inputs by falling back for empty or falsy submissions, such as $username = $_POST['username'] ?: 'Guest';, which assigns 'Guest' if the input is empty or false-equivalent. For configuration files, it enables fallback values for optional settings, like $timeout = $config['timeout'] ?: 30;, ensuring a sensible default without explicit null checks. The Elvis operator complements the null coalescing operator ?? by addressing a broader range of falsy cases, though ?? is preferred when preserving empty strings or zeros is desired. As of PHP 8.4 (2025), the operator remains unchanged.

Comparisons

Ternary Operator

The ternary operator, commonly denoted as condition ? trueExpr : falseExpr, serves as a concise conditional expression in many programming languages, evaluating the condition and returning one of two expressions based on its truthiness. In contrast, the Elvis operator (?:) functions as a specialized shorthand derived from the ternary operator, specifically when the condition checks the truthiness of the left operand itself, such as in patterns like x ? x : y, which simplifies to x ?: y. This structural difference positions the Elvis operator as a targeted variant for providing default values, thereby streamlining code that would otherwise require the full ternary syntax. Key distinctions arise in their flexibility and application: the ternary operator accommodates arbitrary conditions and expressions on both sides of the colon, enabling complex conditional logic beyond mere default assignments. The Elvis operator, however, is inherently limited to scenarios where the left 's evaluation determines the outcome, focusing on falsy or checks without needing to repeat the operand, which reduces verbosity and potential refactoring errors. As a result, the Elvis operator builds on the ternary's foundational conditional mechanism but optimizes for common null-handling patterns. In practice, the ternary operator is preferred for intricate decision-making involving multiple variables or computations, whereas the Elvis operator excels in straightforward default-value scenarios, such as assigning fallbacks for potentially references, promoting cleaner and more maintainable code in null-prone environments. This specialization allows developers to select the ternary for general-purpose conditionals and reserve the Elvis for its niche efficiency in truthiness-based defaults.

Null-Coalescing Operator

The null-coalescing operator, typically denoted by ??, is a binary operator present in various programming languages that returns its left-hand operand if that operand is not null; otherwise, it returns the right-hand operand. This operator specifically targets values for handling, treating all non- values—including falsy ones like false, 0, or empty strings—as valid results from the left side. In comparison to the Elvis operator ?:, the null-coalescing operator performs a narrower check limited to null detection, whereas the Elvis operator evaluates the left operand based on broader truthiness criteria in languages where it is implemented, such as considering empty strings or zero as triggering the default value. This distinction arises because null-coalescing is designed for strict null safety in statically typed languages like C# and , providing safer behavior by not overriding non-null but falsy values, while the Elvis operator offers more concise defaults in dynamic contexts like , where "Groovy truth" encompasses multiple falsy conditions beyond just null. The null-coalescing operator is particularly suited for explicit null handling in API responses or data processing, where distinguishing null from other falsy states prevents unintended defaults for valid but empty inputs. By contrast, the Elvis operator aligns better with general default assignments in user input validation within dynamic environments. Both operators serve to shorten conditional expressions but diverge significantly in their handling of falsy values beyond null. The null-coalescing operator first appeared in C# 2.0 in 2005 and has since been adopted in languages like (introduced in 2014), though it is sometimes confused with the Elvis operator due to their similar syntactic roles in providing defaults; however, it lacks the visual resemblance to Elvis Presley's hairstyle that inspired the Elvis operator's name, and its base form supports chaining (e.g., a ?? b ?? c) similar to some Elvis variants but without truthiness evaluation.

References

  1. [1]
    Operators - The Apache Groovy programming language
    Usage of the Elvis operator reduces the verbosity of your code and reduces the risks of errors in case of refactorings, by removing the need to duplicate the ...Arithmetic operators · Conditional operators · Object operators · Other operators
  2. [2]
    Null safety | Kotlin
    ### Definition, Syntax, Usage of Elvis Operator
  3. [3]
    Why were Null-Safe Operators (e.g. "Elvis operator") rejected as part ...
    Oct 19, 2017 · The Elvis operator has been proposed for every version of Java since 7, and has been rejected every time. Different languages fall on different ...
  4. [4]
    The Ternary & Elvis Operators
    Apr 13, 2023 · The Elvis operator, on the other hand, was introduced in Apache Groovy in 2007, and PHP 5.3 in 2009, and has since been adopted by other ...
  5. [5]
    Comparison - Manual - PHP
    Comparison operators, as their name implies, allow you to compare two values. You may also be interested in viewing the type comparison tables.
  6. [6]
    Kotlin Elvis Operator | Baeldung on Kotlin
    Mar 19, 2024 · The operator returns the first expression if it is not null, or it returns the second expression otherwise. By using the Elvis operator, we can ...
  7. [7]
    Groovy 1.5 release notes
    After the successful release of Groovy 1.0 in January 2007, the next major milestone with the 1.5 label already hits the shelves.
  8. [8]
    The Elvis Operator :: Spring Framework
    The Elvis operator is a shortening of the ternary operator syntax and is used in the Groovy language. With the ternary operator syntax, you usually have to ...
  9. [9]
    What's New in Groovy 1.5 - InfoQ
    Dec 9, 2007 · As this construct is pretty common, the Elvis operator was introduced to simplify such recurring cases, and the statements become: String ...A Groovier Groovy And Why It... · Java 5 Additions · Elvis Operator
  10. [10]
  11. [11]
    Expressions - Kotlin language specification
    The type of elvis operator expression is the least upper bound of the non-nullable variant of the type of the left-hand side expression and the type of the ...
  12. [12]
    org.codehaus.groovy » groovy » 1.5.0 - Maven Repository
    Apache Groovy » 1.5.0 ; http://groovy.codehaus.org/ · Dec 07, 2007 · pom (25 KB) jar (2.1 MB) View All · CentralGroovyLibsGroovyPluginsMulesoftSonatypeWSO2 Public.
  13. [13]
    A history of the Groovy programming language - ACM Digital Library
    Jun 12, 2020 · Groovy was created as a complementary language to Java—its dynamic counterpart. It would look and feel like Java but focus on extensibility and ...
  14. [14]
    The Elvis operator | Ars OpenForum - Ars Technica
    May 13, 2024 · Wikipedia said: The name "Elvis operator" refers to the fact that when its common notation, ?:, is viewed sideways, it resembles an emoticon of ...
  15. [15]
    Groovy Elvis Operator - java - Stack Overflow
    Mar 23, 2015 · In Groovy, it is called the Elvis operator because if you turn the ?: 90 degrees clockwise/ to the right of your screen, the ? looks like Elvis Presley's hair ...What is the "?:" operator used for in Groovy?Elvis operator and type casting precedence in GroovyMore results from stackoverflow.com
  16. [16]
  17. [17]
    Gradle Goodness: Get Property Value With findProperty - JDriven Blog
    May 26, 2016 · With the new findProperty method and the Groovy elvis operator ( ?: ) we can try to get a property value and if not found return a default value ...
  18. [18]
    Release notes for Groovy 4.0
    Groovy 4.0 includes new features, streamlines legacy aspects, has a Maven coordinate change, and removes legacy classes. Some features are incubating.Missing: Elvis | Show results with:Elvis
  19. [19]
  20. [20]
    Type checks and casts | Kotlin Documentation
    Nov 6, 2024 · In Kotlin, you can perform type checks to check the type of an object at runtime. Type casts enable you to convert objects to a different type.Missing: Elvis | Show results with:Elvis
  21. [21]
  22. [22]
    Use common Kotlin patterns with Android
    You can instead handle null cases immediately by using an Elvis operator ( ?: ), as shown in the following example: ... Note: View binding solutions like Data ...
  23. [23]
    What's new in Kotlin 1.9.0
    Jul 6, 2023 · There's now also basic support for Kotlin/Native and multiplatform projects. Compatibility of the kapt compiler plugin with the K2 compiler.Missing: safety | Show results with:safety
  24. [24]
    What's new in Kotlin 1.9.20
    Nov 1, 2023 · The Kotlin 1.9.20 release is out, the K2 compiler for all the targets is now in Beta, and Kotlin Multiplatform is now Stable. Additionally, here ...
  25. [25]
    null-coalescing operators - C# reference | Microsoft Learn
    The `??` and `??=` operators are the C# null-coalescing operators. They return the value of the left-hand operand if it isn't null.Missing: official | Show results with:official