Recent from talks
Nothing was collected or created yet.
Elvis operator
View on Wikipedia

In certain computer programming languages, the Elvis operator, often written ?:, is a binary operator that evaluates its first operand and returns it if its value is logically true (according to a language-dependent convention, in other words, a truthy value), and otherwise evaluates and returns its second operand. The second operand is only evaluated if it is to be returned (short-circuit evaluation). The notation of the Elvis operator was inspired by the ternary conditional operator, ? :, since the Elvis operator expression A ?: B is approximately equivalent to the ternary conditional expression A ? A : B.
The name "Elvis operator" derives from the resemblance of the notation ?:, when viewed sideways, to an emoticon of Elvis Presley with his signature hairstyle.[1]
A similar operator is the null coalescing operator, where the boolean truth(iness) check is replaced with a check for non-null instead. This is usually written ??, and can be seen in languages like C#[2] or Dart.[3]
Alternative syntaxes
[edit]In several languages, such as Common Lisp, Clojure, Lua, Object Pascal, Perl, Python, Ruby, and JavaScript, there is no need for the Elvis operator, because the language's logical disjunction operator (typically || or or) is short-circuiting and returns its first operand if it would evaluate to a truthy value, and otherwise its second operand, which may be a truthy or falsy value (rather than a Boolean true or false value, such as in C and C++). These semantics are identical to the Elvis operator.
Example
[edit]Boolean variant
[edit]In a language that supports the Elvis operator, something like this:
x = f() ?: g()
will set x equal to the result of f() if that result is truthy, and to the result of g() otherwise.
It is equivalent to this example, using the conditional ternary operator:
x = f() ? f() : g()
except that it does not evaluate f() twice if it yields truthy. Note the possibility of arbitrary behaviour if f() is not a state-independent function that always returns the same result.
Object reference variant
[edit]This code will result in a reference to an object that is guaranteed to not be null. Function f() returns an object reference instead of a boolean, and may return null, which is universally regarded as falsy:
x = f() ?: "default value"
Languages supporting the Elvis operator
[edit]- In GNU C and C++ (that is: in C and C++ with GCC extensions), the second operand of the ternary operator is optional.[4] This has been the case since at least GCC 2.95.3 (March 2001), and seems to be the original Elvis operator.[5]
- In Apache Groovy, the "Elvis operator"
?:is documented as a distinct operator;[6] this feature was added in Groovy 1.5[7] (December 2007). Groovy, unlike GNU C and PHP, does not simply allow the second operand of ternary?:to be omitted; rather, binary?:must be written as a single operator, with no whitespace in between. - In PHP, it is possible to leave out the middle part of the ternary operator since PHP 5.3.[8] (June 2009).
- The Fantom programming language has the
?:binary operator that compares its first operand withnull. - In Kotlin, the Elvis operator returns its left-hand side if it is not null, and its right-hand side otherwise.[9] A common pattern is to use it with
return, like this:val foo = bar() ?: return - In Gosu, the
?:operator returns the right operand if the left is null as well. - In C#, the null-conditional operator,
?.is referred to as the "Elvis operator",[10] but it does not perform the same function. Instead, the null-coalescing operator??does. - In ColdFusion and CFML, the Elvis operator was introduced using the
?:syntax. - The Xtend programming language has an Elvis operator.[11]
- In Google's Closure Templates, the Elvis operator is a null coalescing operator, equivalent to
isNonnull($a) ? $a : $b.[12] - In Ballerina, the Elvis operator
L ?: Rreturns the value ofLif it's not nil. Otherwise, return the value ofR.[13] - In JavaScript, the nullish coalescing (
??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand isnullorundefined, and otherwise returns its left-hand side operand.[14] - In Perl there is a logical short-circuiting disjunction
||and a similar lower precedenceor.[15] They differ from the bitwise or operator|which evaluates both operands without short-circuiting. There is also a corresponding assignment operator||=that evaluates its right-hand operand and assigns it to the left-operand unless the logical value of the left-operand is true. There is also a short-circuiting defined-or operator//which evaluates its right-operand and returns its value only if the left-operand is undefined. Finally, the corresponding assignment operator is//=. Similar exclusive-or operators are not Elvis operators as they do not short-circuit. Other short-circuiting operators are the logical-and ones&&andand, but their behavior is opposite that of the Elvis operator.
See also
[edit]?:or conditional operator, when used as a ternary operator- Null coalescing operator,
??operator - Safe navigation operator, often
?. - Spaceship operator
<=> - Option type
References
[edit]- ^ Joyce Farrell (February 7, 2013). Java Programming. Cengage Learning. p. 276. ISBN 978-1285081953.
The new operator is called Elvis operator because it uses a question mark and a colon together (?:); if you view it sideways, it reminds you of Elvis Presley.
- ^ "?? Operator". C# Reference. Microsoft. Retrieved December 5, 2018.
- ^ "Conditional expressions". Dart Language. Google.
- ^ "Conditionals (Using the GNU Compiler Collection (GCC)): Conditionals with Omitted Operands". gcc.gnu.org. Retrieved January 14, 2026.
- ^ "Using and Porting the GNU Compiler Collection (GCC): C Extensions". gcc.gnu.org.
- ^ "Elvis Operator (?: )".
- ^ "The Apache Groovy programming language - Groovy 1.5 release notes". groovy-lang.org.
- ^ "PHP: Comparison Operators - Manual". PHP website. Retrieved February 17, 2014.
- ^ "Null Safety - Kotlin Programming Language". Kotlin.
- ^ Albahari, Joseph; Albahari, Ben (2015). C# 6.0 in a Nutshell (6 ed.). O'Reilly Media. p. 59. ISBN 978-1491927069.
- ^ Efftinge, Sven. "Xtend - Expressions". eclipse.org.
- ^ "Closure Templates - Expressions". GitHub. October 29, 2021.
- ^ "Elvis Operator - Ballerina Programming Language". Ballerina. Archived from the original on December 20, 2018. Retrieved December 19, 2018.
- ^ "Nullish coalescing operator (??) - JavaScript | MDN". developer.mozilla.org. Retrieved January 5, 2023.
- ^ "perlop". Retrieved July 9, 2025.
Elvis operator
View on Grokipedia?:, is a binary operator featured in various programming languages that evaluates its left operand and returns it if the operand is not null (in null-safe languages) or truthy (according to the language's truthiness rules in other languages); otherwise, it returns the right operand.[1] This construct acts as a shorthand for the ternary conditional operator (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.[2] For example, in Groovy, the expression user.name ?: 'Anonymous' evaluates to the user's name if available, or 'Anonymous' as a fallback.[1]
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.[3] First popularized in the Groovy programming language around 2007, it quickly influenced other dynamic and statically typed languages seeking concise null-handling syntax.[4]
In Groovy, 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 defensive programming against unexpected nulls.[1] Kotlin employs it prominently within its robust null safety system, often chained with the safe call operator (?.) to avoid null pointer exceptions, as in val length = text?.length ?: 0.[2] 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'.[5] 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 Groovy.[6]
Fundamentals
Definition
The Elvis operator, denoted as?:, is a binary operator in certain programming languages that evaluates its left operand 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.[1] This operator serves as a shorthand for conditional expressions where the condition is implicitly the truthiness of the left operand itself.[7]
In conceptual terms, the Elvis operator can be understood through pseudocode as result = (left is truthy) ? left : right, effectively omitting the explicit condition from a full ternary operator while preserving the same logical outcome for null or falsy checks.[8] It thus streamlines the assignment of default values or the handling of potentially absent data, reducing boilerplate code that would otherwise require verbose if-else statements or explicit ternary conditions.[9]
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.[1] The Elvis operator first appeared in Apache Groovy version 1.5, released in December 2007.[7]
Purpose
The Elvis operator primarily simplifies null-safe default value assignments by providing a shorthand 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.[1][2] Among its key benefits, the operator enhances code readability by streamlining verbose conditional logic into a single, intuitive expression, thereby minimizing cognitive overhead for maintainers. It also prevents null pointer 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.[1][2] The operator addresses common pain points in software development, including the handling of optional values and the provision of fallbacks in APIs, particularly emphasizing error prevention in dynamic languages where type safety 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.[1][2]Syntax
Basic Syntax
The Elvis operator is denoted by the notationexpression1 ?: expression2, where it evaluates expression1 and returns its value if truthy (according to the language's rules), otherwise returning expression2.[1][2] This binary operator serves as a shorthand for providing a default value, mirroring the structure of a ternary conditional but omitting the explicit repetition of the condition.[1]
In terms of grammar rules, the Elvis operator has a precedence level higher than assignment operators but lower than logical AND (&&) and OR (||) operators, ensuring that logical operations bind more tightly in mixed expressions.[1][10] It is right-associative, meaning that in chained expressions like a ?: b ?: c, the operator groups as a ?: (b ?: c).[1][10] The operator must appear within expression contexts, such as variable assignments, return statements, or other positions where a value is expected, and it cannot standalone as a statement.[1]
Evaluation proceeds by first assessing expression1 for truthiness or null (depending on the language); if it qualifies, expression2 is not evaluated due to short-circuiting behavior, which optimizes performance by avoiding unnecessary computations.[1][2] 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 operand, typically the type of the non-null or truthy expression, allowing for flexible type handling in both dynamic and static contexts.[2][1]
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 properties while providing a default if any part of the chain is null.[1] This variant extends the basic syntax by integrating null-safe property access before applying the default value logic.[1] Specific implementations of the Elvis operator vary in their evaluation criteria: the truthy/falsy variant treats the left operand as falsy (including null, false, zero, or empty collections) and returns the right operand only if the left is falsy, as seen in Groovy.[1] In contrast, the null-specific form checks exclusively for null values on the left operand, ignoring other falsy states, which is the approach in Kotlin.[10] Additionally, assignment forms exist, such as the Elvis assignment operator introduced in Groovy 3.0, which assigns a default value to a variable only if it is currently null.[1] 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) operand, providing a concise way to specify hierarchical fallback values.[1] 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.[10]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.[2][1] This functionality streamlines code by avoiding verbose conditional checks for null values, promoting readability in scenarios where defaults are essential. A representative example in pseudocode illustrates this behavior:name = userInput ?: 'Anonymous'
name = userInput ?: 'Anonymous'
userInput evaluates to a non-null value, name is assigned that value; otherwise, it defaults to the string 'Anonymous'.[1] This demonstrates the operator's role in providing a fallback, akin to a shorthand for name = userInput != null ? userInput : 'Anonymous'.[2]
In PHP (version 5.3 and later), it checks for falsy values:
$name = $userInput ?: 'Anonymous';
$name = $userInput ?: 'Anonymous';
$userInput is truthy, $name is set to it; otherwise, to 'Anonymous'. Falsy includes null, empty strings, false, or zero.[5]
The evaluation proceeds step-by-step: the left expression is assessed first for nullity (or falsiness in some implementations, encompassing null, 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.[2][1] The output type is typically the common supertype of both operands, preserving type safety without implicit conversions unless specified.[2] No inherent side effects arise from the operator itself, though the expressions involved may introduce them if not designed carefully.
In API 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 placeholder if the server omits the field: profileImage = apiResponse.imageUrl ?: defaultPlaceholder.[2] This approach ensures robust data processing without null pointer 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.[1]
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 Groovy 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 pseudocode, the expressionfullName = user?.name ?: 'Unknown' safely retrieves the name property from a user object only if user is non-null; otherwise, it defaults to 'Unknown', preventing runtime errors during property access.[1][2] Note that PHP 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 null upon encountering a null reference, thereby avoiding exceptions. The Elvis operator (?:) then evaluates this result: if it is non-null, the value is used; if null, 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.[1][2]
A common scenario for this feature arises in data processing tasks, such as traversing object graphs during JSON parsing or executing ORM 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 API responses, reducing boilerplate null checks.[1][2]
This integration promotes the creation of fluent interfaces, where method chaining can proceed without interspersed explicit null guards, thereby enhancing code readability and maintainability in large-scale applications.[1][2]
History
Origin
The Elvis operator was first implemented in Groovy version 1.5, released on December 7, 2007, as a shorthand for the ternary operator specifically tailored for dynamic scripting on the Java platform.[7][11] This operator, denoted as?:, allows for concise assignment of default values when the primary expression evaluates to null or false according to Groovy's truth rules, thereby reducing boilerplate code common in Java-like environments.[7][9]
The operator was proposed during the language's maturation phase in mid-2007 under the leadership of project manager Guillaume Laforge.[12][9] Laforge led the Groovy development team in integrating this feature to address the verbosity of explicit null checks and conditional expressions in Java-influenced syntax, enhancing code readability and maintainability for scripting tasks.[9][12] The proposal emerged as part of Groovy's broader evolution from a simple Java scripting tool—initially conceived in 2003—to a more expressive language supporting advanced features like annotations and generics alongside Java 5 compatibility.[7][12]
This addition aimed to bolster Groovy's utility in domains requiring rapid development, such as web application frameworks like Grails and build automation systems like Gradle, both of which leveraged Groovy's dynamic nature for configuration and scripting.[9][12] By streamlining null-safe operations, the Elvis operator contributed to Groovy's goal of providing a more fluid alternative to Java for these use cases, influencing subsequent language designs.[7]
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.[6][13]
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.[7] The name rapidly spread through developer blogs, forums, and community discussions, establishing it as a playful yet enduring reference in programming literature.[14]
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.[2]
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 PHP and Perl, which evokes a flying craft, or Python's "walrus operator" (:=), reminiscent of the animal's tusks.
Implementations
Groovy
The Elvis operator (?:) was introduced in Groovy 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.[7] 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.[1]
Unique to Groovy, 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.[15] This integration aligns with Groovy's dynamic nature, allowing the operator to work seamlessly in expressions involving closures 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 Gradle 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.[16] 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 Groovy DSLs.
As of Groovy 5.0.0 (released in 2024), enhancements in Java 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.[17][18]
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.[19] 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.[2] 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 type safety.[2]
A distinctive feature of the Elvis operator in Kotlin is its integration with the language's nullable type system, where types are non-nullable by default and marked as nullable with a trailing question mark (e.g., String?). The compiler 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.[2] Following the Elvis operator, if the right-hand side provides a non-null value, the compiler performs a smart cast on the result, treating it as non-nullable for subsequent operations within the scope, enhancing type inference without explicit casts.[20] This aligns with Kotlin's annotations for nullability in Java interoperability, such as mapping Java's @Nullable to Kotlin's nullable types, ensuring seamless handling of legacy code.[21]
In practice, the Elvis operator is widely used in Android development for safe data handling, particularly in UI data binding where nullable model properties (e.g., from network responses) require defaults to prevent crashes in view rendering.[22] For example:
val displayName: [String](/page/String) = user?.name ?: "Anonymous User"
val displayName: [String](/page/String) = user?.name ?: "Anonymous User"
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.[5] 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.[5]
This operator short-circuits similarly to the logical OR (||) operator, meaning the right operand expr2 is not evaluated if expr1 is truthy, which can improve performance and avoid side effects in the fallback expression.[5] However, it does not suppress notices for undefined variables; attempting to use an undefined variable as expr1 will trigger an E_NOTICE, unlike the null coalescing operator ?? introduced in PHP 7.0. For example:
$value = $undefinedVar ?: 'default'; // Triggers E_NOTICE for undefined $undefinedVar
$value = $undefinedVar ?: 'default'; // Triggers E_NOTICE for undefined $undefinedVar
null or unset variables should trigger a fallback, but developers must ensure variables are defined to avoid warnings.[5]
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.[5] 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.[5][26]
Comparisons
Ternary Operator
The ternary operator, commonly denoted ascondition ? 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.[1] 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.[1] 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.[2]
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 operand's evaluation determines the outcome, focusing on falsy or null checks without needing to repeat the operand, which reduces verbosity and potential refactoring errors.[1] As a result, the Elvis operator builds on the ternary's foundational conditional mechanism but optimizes for common null-handling patterns.[2]
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 null references, promoting cleaner and more maintainable code in null-prone environments.[2] This specialization allows developers to select the ternary for general-purpose conditionals and reserve the Elvis for its niche efficiency in truthiness-based defaults.[1]