Elvis operator

Last updated

In certain computer programming languages, the Elvis operator, often written ?:, is a binary operator that returns the evaluated first operand if that operand evaluates to a value likened to logically true (according to a language-dependent convention, in other words, a truthy value), and otherwise returns the evaluated second operand (in which case the first operand evaluated to a value likened to logically false, in other words, a falsy value). This is identical to a short-circuit or with "last value" semantics. 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.

Contents

The name "Elvis operator" refers to the fact that when its common notation, ?:, is viewed sideways, it resembles 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

In several languages, such as Common Lisp, Clojure, Lua, Object Pascal, Perl, Python, Ruby, and JavaScript, the logical disjunction operator (typically || or or) has the same behavior as the above: returning its first operand if it would evaluate to a truthy value, and otherwise evaluating and returning its second operand, which may be a truthy or falsy value. When the left-hand side is truthy, the right-hand side is not even evaluated; it is "short-circuited". This is different than the behavior in other languages such as C/C++, where the result of || will always be a (proper) boolean.

Example

Boolean variant

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

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

See also

Related Research Articles

In logic, mathematics, and computer science, arity is the number of arguments or operands taken by a function, operation or relation. In mathematics, arity may also be called rank, but this word can have many other meanings. In logic and philosophy, arity may also be called adicity and degree. In linguistics, it is usually named valency.

In computer programming, specifically when using the imperative programming paradigm, an assertion is a predicate connected to a point in the program, that always should evaluate to true at that point in code execution. Assertions can help a programmer read the code, help a compiler compile it, or help the program detect its own defects.

In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location(s) denoted by a variable name; in other words, it copies a value into the variable. In most imperative programming languages, the assignment statement is a fundamental construct.

<span class="mw-page-title-main">Conditional (computer programming)</span> Control flow statement that executes code according to some condition(s)

In computer science, conditionals are programming language constructs that perform different computations or actions or return different values depending on the value of a Boolean expression, called a condition.

This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, ternary if, or inline if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is the most common, but alternative syntax do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.

In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.

In computer science, the Boolean is a data type that has one of two possible values which is intended to represent the two truth values of logic and Boolean algebra. It is named after George Boole, who first defined an algebraic system of logic in the mid 19th century. The Boolean data type is primarily associated with conditional statements, which allow different actions by changing control flow depending on whether a programmer-specified Boolean condition evaluates to true or false. It is a special case of a more general logical data type—logic does not always need to be Boolean.

In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality and inequalities.

<span class="mw-page-title-main">Null (SQL)</span> Marker used in SQL databases to indicate a value does not exist

In SQL, null or NULL is a special marker used to indicate that a data value does not exist in the database. Introduced by the creator of the relational database model, E. F. Codd, SQL null serves to fulfil the requirement that all true relational database management systems (RDBMS) support a representation of "missing information and inapplicable information". Codd also introduced the use of the lowercase Greek omega (ω) symbol to represent null in database theory. In SQL, NULL is a reserved word used to identify this marker.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

In computing, IIf is a function in several editions of the Visual Basic programming language and ColdFusion Markup Language (CFML), and on spreadsheets that returns the second or third parameter based on the evaluation of the first parameter. It is an example of a conditional expression, which is similar to a conditional statement.

The conditional operator is supported in many programming languages. This term usually refers to ?: as in C, C++, C#, and JavaScript. However, in Java, this term can also refer to && and ||.

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type. In statically typed languages, a nullable type is an option type, while in dynamically typed languages, equivalent behavior is provided by having a single null value.

C's offsetof macro is an ANSI C library feature found in stddef.h. It evaluates to the offset of a given member within a struct or union type, an expression of type size_t. The offsetof macro takes two parameters, the first being a structure or union name, and the second being the name of a subobject of the structure/union that is not a bit field. It cannot be described as a C prototype.

The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, such as : C# since version 2.0, Dart since version 1.12.0, PHP since version 7.0.0, Perl since version 5.10 as logical defined-or, PowerShell since 7.0.0, and Swift as nil-coalescing operator.

In programming jargon, Yoda conditions is a programming style where the two parts of an expression are reversed from the typical order in a conditional statement. A Yoda condition places the constant portion of the expression on the left side of the conditional statement.

Kotlin is a cross-platform, statically typed, general-purpose high-level programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin's standard library depends on the Java Class Library, but type inference allows its syntax to be more concise. Kotlin mainly targets the JVM, but also compiles to JavaScript or native code via LLVM. Language development costs are borne by JetBrains, while the Kotlin Foundation protects the Kotlin trademark.

In object-oriented programming, the safe navigation operator is a binary operator that returns null if its first argument is null; otherwise it performs a dereferencing operation as specified by the second argument.

References

  1. Joyce Farrell (7 February 2013). Java Programming. 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.
  2. "?? Operator". C# Reference. Microsoft. Retrieved 5 December 2018.
  3. "Conditional expressions". Dart Language. Google.
  4. "Using the GNU Compiler Collection (GCC): Conditionals with omitted operands". gcc.gnu.org.
  5. "Using and Porting the GNU Compiler Collection (GCC): C Extensions". gcc.gnu.org.
  6. "Elvis Operator (?: )".
  7. "The Apache Groovy programming language - Groovy 1.5 release notes". groovy-lang.org.
  8. "PHP: Comparison Operators - Manual". PHP website. Retrieved 2014-02-17.
  9. "Null Safety - Kotlin Programming Language". Kotlin.
  10. Albahari, Joseph; Albahari, Ben (2015). C# 6.0 in a Nutshell (6 ed.). O'Reilly Media. p. 59. ISBN   978-1491927069.
  11. Efftinge, Sven. "Xtend - Expressions". eclipse.org.
  12. "Closure Templates - Expressions". GitHub. 29 October 2021.
  13. "Elvis Operator - Ballerina Programming Language". Ballerina. Archived from the original on 2018-12-20. Retrieved 2018-12-19.
  14. "Nullish coalescing operator (??) - JavaScript | MDN". developer.mozilla.org. Retrieved 2023-01-05.