Why is the Elvis operator not more common? - Programming Language Design and Implementation Stack Exchange
Thoughts on the Null Coalescing (??) operator precedence?
What does ?: do in Kotlin? (Elvis Operator) - Stack Overflow
Why is there no classic '?:' ternary operator in Kotlin?
What is the purpose of the ?: operator (Elvis Operator) in Kotlin?
What is the Elvis operator in Kotlin?
How to write the Elvis operator in Kotlin?
Many popular mainstream languages that focus at least somewhat on conciseness have a similar operator, so I'd say that it is fairly common.
First, some notes:
- For the purposes of this answer, it doesn't matter whether the syntax is
?:,??,||oror, especially since all are equally concise. - What is a "true value" for this operator differs from language to language, and may not be the same as what is considered a "true value" in other contexts (like in an
ifcondition).
Now, let's go though some languages and see what we find:
- C and C++: no Elvis in the standards, since concise syntax sugar does not seem to be focus for these languages
- Java: Elvis was explicitly rejected, seemingly also because syntax sugar is not a focus for Java.
- C#:
??is anull-checking Elvis - Python:
orworks as truthy-checking Elvis - JavaScript:
||works as an Elvis operator that checks for truthiness,??is an Elvis operator that only checks fornullandundefined - PHP:
?:is a truthy-checking Elvis,??is anull-checking Elvis - Ruby:
||works as a truthy-checking Elvis - Go: no Elvis, since Go prefers simplicity of language to conciseness of code
- Swift:
??is anil-checking Elvis - Rust: no Elvis, presumably because Rust does not have concepts similar to truthiness or
null
Some languages simply don't have (a relevant type of) nulls, or don't have the concept of non-Boolean thruthiness, making it a not applicable feature.
Many languages have a "null-coalescing" operator: a binary operator used to unwrap an optional/nullable value, or provide a "default" value if the LHS is null/none. It's usually spelled ?? (as in Javascript, Swift, C#, etc.).
I'm pondering the precedence of such an operator.
Why not just use no precedence? Parenthesis! S-expressions! Polish!
All interesting ideas! But this post will focus on a more "C-style" language perspective.
As for ??, it seems like there's a bit of variety. Let's start with a kind of basic operator precedence for a hypothetical C-style statically typed language with relatively few operators:
| prec | operators | types |
|---|---|---|
| 1 | Suffixes: a() | -> any type |
| 2 | High-prec arithmetic: a * b | integer, integer -> integer |
| 3 | Low-prec arithmetic: a + b | integer, integer -> integer |
| 4 | Comparisons: a == b | integer, integer -> boolean |
| 5 | Logic: a && b | boolean, boolean -> boolean |
There are subtly differences here and there, but this is just for comparisons. Here's how (some) different languages handle the precedence.
Below #5:
C#
PHP
Dart
Equal to #5
Javascript (Kinda;
??must be disambiguated from&&and||)Between #3 and #4:
Swift
Zig
Kotlin
So, largely 2 camps: very low precedence, or moderately low. From a brief look, I can't find too much information on the "why" of all of this. One thing I did see come up a lot is this: ?? is analogous to ||, especially if they both short-circuit. And in a lot of programming languages with a looser type system, they're the same thing. Python's or comes to mind. Not relevant to a very strict type system, but at least it makes sense why you would put the precedence down that. Score 1 for the "below/equal 5" folk.
However, given the divide, it's certainly not a straightforward problem. I've been looking around, and have found a few posts where people discuss problems with various systems.
https://forums.swift.org/t/nil-coalescing-operator-precedence/2954
https://www.codeproject.com/Tips/721145/Beware-The-null-coalescing-operator-is-low-in-the
These seem to center around this construct: let x = a() ?? 0 + b() ?? 0. Operator precedence is largely cultural/subjective. But if I were a code reviewer, attempting to analyze a programmer's intent, it seems pretty clear to me that the programmer of this wanted x to equal the sum of a() and b(), with default values in case either were null. However, no one parses ?? as having a higher precedence than +.
This example might be a bit contrived. To us, the alternate parse of let x = a() ?? (0 + b()) ?? 0 because... why would you add to 0? And how often are you chaining null coalescing operators? (Well, it can happen if you're using optionals, but it's still rare). But, it's a fairly reasonable piece of code. Those links even have some real-world examples like this people have fallen for.
Looking at this from a types perspective, I came to this conclusion; In a strongly-typed language, operator precedence isn't useful if operators can't "flow" from high to low precedence due to types.
To illustrate, consider the expression x + y ?? z. We don't know what the types of x, y, and z are. However, if ?? has a lower precedence than +, this expression can't be valid in a strictly typed language, where the LHS of ?? must be of an optional/nullable type.
If you look back at our hypothetical start table, you can see how operator types "flow" through precedence. Arithmetic produces integers, which can be used as arguments to comparisons. Comparisons produce booleans, which can be used as arguments to logical operators.
This is why I'd propose that it makes sense for ?? to have a precedence, in our example, between 1 and 2. That way, more "complex" types can "decay" though the precedence chain. Optionals are unwrapped to integers, which are manipulated by arithmetic, decayed to booleans by comparison, and further manipulated by logic.
Discussion questions:
What are some reasons for choosing the precedence of
??other than the ones discussed?Have any other languages done something different with the precedence, and why?
Has anyone put the precedence of
??above arithmetic?
Thanks!
TL;DR: If the resulting object reference [first operand] is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned. Additionally, the operator can throw an exception if null is returned.
The Elvis operator is part of many programming languages, e.g. Kotlin but also Groovy or C#. I find the Wikipedia definition pretty accurate:
In certain computer programming languages, the Elvis operator
?:is a binary operator that returns its first operand if that operand istrue, and otherwise evaluates and returns its second operand. It is a variant of the ternary conditional operator,? :, found in those languages (and many others): the Elvis operator is the ternary operator with its second operand omitted.
The following is especially true for Kotlin:
Some computer programming languages have different semantics for this operator. Instead of the first operand having to result in a boolean, it must result in an object reference. If the resulting object reference is not
null, it is returned. Otherwise the value of the second operand (which may benull) is returned. If the second operand is null, the operator is also able to throw an exception.
An example:
x ?: y // yields `x` if `x` is not null, `y` otherwise.
x ?: throw SomeException() // yields `x` if `x` is not null, throws SomeException otherwise
The Elvis Operator is represented by a question mark followed by a colon: ?: and it can be used with this syntax:
first operand ?: second operand
It enables you to write a consise code, and works as such:
If first operand isn't null, then it will be returned. If it is null, then the second operand will be returned. This can be used to guarantee that an expression won't return a null value, as you'll provide a non-nullable value if the provided value is null.
For example(in Kotlin):
fun retrieveString(): String { //Notice that this type isn't nullable
val nullableVariable: String? = getPotentialNull() //This variable may be null
return nullableVariable ?: "Secondary Not-Null String"
}
In this case, if the computed value of getPotentialNull is not null, it will be returned by retrieveString; If it is null, the second expression "Secondary Not-Null String" will be returned instead.
Also note that the right-hand side expression is evaluated only if the left-hand side is null.
In Kotlin, you could use any expression as second operand, such as a throw Exception expression
return nullVariable ?: throw IllegalResponseException("My inner function returned null! Oh no!")
The name Elvis Operator comes from the famous American singer Elvis Presley. His hairstyle resembles a Question Mark

Source: Wojda, I. Moskala, M. Android Development with Kotlin. 2017. Packt Publishing
Greetings! I am a developer with a lot of experience and have written in many languages. Not so long ago, I started switching from Java to Kotlin. I really like Kotlin's brevity compared to Java. But when I came across the implementation of the ternary operator, I was struck by its bulkiness.
if (condition) a else b
I understand that the ternary operator cannot be replaced with a similar one from Java/TS/etc:
condition ? a : b
Because of the Elvis already existing in the language
value ?: alternative
But why was the semantics not adopted, for example, from TS, where the ternary operator:
condition ? a : b
and nullish coalescing operator:
value ?? alternative
Is the double question mark ('??') already used in Kotlin?
Having significantly searched internet for the reasons for this decision, I did not find a complete answer. Just a lot of questions from other developers and answers in the style of "well, because it happened that way."
So, Why?
Might be a simple question, but with null safety available in Kotlin, do you check for null?
Do you write:
if(elem != null){
print(elem.toString());
}or do you just do:
print(elem?.toString());
This is just a small example, but just to get the idea of the question