Hubbry Logo
Elvis operatorElvis operatorMain
Open search
Elvis operator
Community hub
Elvis operator
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Elvis operator
Elvis operator
from Wikipedia

Elvis Presley, whose hair resembles the operator viewed sideways

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 with null.
  • 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 ?: R returns the value of L if it's not nil. Otherwise, return the value of R.[13]
  • In JavaScript, the nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.[14]
  • In Perl there is a logical short-circuiting disjunction || and a similar lower precedence or.[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 && and and, but their behavior is opposite that of the Elvis operator.

See also

[edit]

References

[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
The Elvis operator, denoted by the symbol ?:, is a binary operator featured in various programming languages that evaluates its left and returns it if the operand is not null (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 operator 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 ternary operator while preserving the same logical outcome for null 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 ternary 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 operator 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 APIs, 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 ternary conditional but omitting the explicit repetition of the condition. In terms of 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. 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 statements, or other positions where a value is expected, and it cannot standalone as a statement. Evaluation proceeds by first assessing expression1 for 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. 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 null. 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 null, 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 null 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 variable only if it is currently null. 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 null values, promoting readability in scenarios where defaults are essential. A representative example in pseudocode illustrates this behavior:

pseudocode

name = userInput ?: 'Anonymous'

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';

$name = $userInput ?: 'Anonymous';

If $userInput is truthy, $name is set to it; otherwise, to 'Anonymous'. Falsy includes null, 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 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. 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 placeholder 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 runtime 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 null upon encountering a null , 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. A common scenario for this feature arises in data processing tasks, such as traversing object graphs during 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 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 null 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 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 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 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. For example:

kotlin

val displayName: [String](/page/String) = user?.name ?: "Anonymous User"

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

$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 null 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 null 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 null values for handling, treating all non-null 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 Swift, 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 Swift (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

Add your contribution
Related Hubs
User Avatar
No comments yet.