🌐
Kotlin Discussions
discuss.kotlinlang.org › t › null-coalescing-operator-wikipedia-entry › 2487
Null Coalescing Operator Wikipedia Entry - Kotlin Discussions
April 10, 2017 - I was reading on Wikipedia about null coalescing operators and found this entry for Kotlin. Kotlin uses the ‘?:’ operator.[16] This is an unusual choice of symbol, given that ?: is typically used for the Elvis operator, not null coalescing, but it was inspired by Groovy (programming language) where null is considered false.
🌐
Kotlin
kotlinlang.org › docs › null-safety.html
Null safety | Kotlin Documentation
The b?.length expression checks for nullability and returns b.length if b is non-null, or null otherwise. The type of this expression is Int?. You can use the ?. operator with both var and val variables in Kotlin:
Discussions

Why is the Elvis operator not more common? - Programming Language Design and Implementation Stack Exchange
$\begingroup$ A null-coalescing operator is rather common ime, it just tends to look different — Swift, JS, and C# all use ?? for that. $\endgroup$ ... $\begingroup$ @Bbrk24 null-coalescing is a little bit different AFAIK? The Boolean check is now check for non-null. $\endgroup$ ... $\begingroup$ Your Kotlin ... More on langdev.stackexchange.com
🌐 langdev.stackexchange.com
May 17, 2023
Thoughts on the Null Coalescing (??) operator precedence?
When something relatively new comes out, it's common for the first few games in town to foul up the artistry. Wirth is a towering intellect in this field, but he screwed up the precedence tables in Pascal. Experience will highlight mistakes, and then it's eventually time to design a new language. ?? clearly goes after function-call and field-access, but before arithmetic. The field-access counterpart .? should be on the same level as non-null field-access .. More on reddit.com
🌐 r/ProgrammingLanguages
11
31
April 30, 2024
What does ?: do in Kotlin? (Elvis Operator) - Stack Overflow
In C# we refer to ?. as the Elvis operator, but it is written differently - . instead of : - and it behaves differently - it is a safe navigation operator. Short-circuit OR operator || and null-coalescing operator ?? cover the behaviors of the original ?: operator, for booleans and references ... More on stackoverflow.com
🌐 stackoverflow.com
Why is there no classic '?:' ternary operator in Kotlin?
The kotlin team made a decision about this a while ago which boils down to "we already have if-else as an expression, so ternary is unnecessary" Personally I love the ternary because it looks cool but their logic is pretty solid for excluding it lol More on reddit.com
🌐 r/Kotlin
59
29
May 1, 2024
People also ask

What is the purpose of the ?: operator (Elvis Operator) in Kotlin?
The purpose of the ?: operator, also known as the Elvis Operator, in Kotlin is to offer a succinct syntax for conditional expressions related to null safety. It allows for a default value to be specified in cases when a variable is found to be null, thus preventing NullPointerExceptions and streamlining null checks.
🌐
dhiwise.com
dhiwise.com › post › kotlin-elvis-operator-the-key-to-safer-null-proof-code
Kotlin Elvis Operator: The Key to Safer, Null-Proof Code
What is the Elvis operator in Kotlin?
The Kotlin Elvis Operator, represented with ?:, is a binary operator that provides a concise way to handle nullability in expressions. It returns the not-null value of its left-hand operand if it's not null or the right-hand side operand if the left is null.
🌐
dhiwise.com
dhiwise.com › post › kotlin-elvis-operator-the-key-to-safer-null-proof-code
Kotlin Elvis Operator: The Key to Safer, Null-Proof Code
How to write the Elvis operator in Kotlin?
To write the Elvis operator in Kotlin, you use the ?: symbol after an expression that can be null. To its right, you provide a non-null value or an alternative expression to be used in case the left-hand side evaluates to null. For example: ```kotlin val result = nullableValue ?: "Default" ``` In this code, if nullableValue is not null, the result will be assigned its value; otherwise, "Default" will be assigned to the result.
🌐
dhiwise.com
dhiwise.com › post › kotlin-elvis-operator-the-key-to-safer-null-proof-code
Kotlin Elvis Operator: The Key to Safer, Null-Proof Code
🌐
Stack Overflow
stackoverflow.com › questions › 75607368 › why-does-the-elvis-operator-null-coalescing-operator-work-this-way-in-kotlin
Why does the Elvis operator/null coalescing operator work this way in Kotlin? - Stack Overflow
I have the following code: companion object { private const val DEFAULT_LANGUAGE_CODE = "en-us" } val currentLanguageCode: String get() { return selectedLang...
binary operator that is part of the syntax for a basic conditional expression in several programming languages
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 (in alphabetical order): C# since version 2.0, … Wikipedia
🌐
Wikipedia
en.wikipedia.org › wiki › Null_coalescing_operator
Null coalescing operator - Wikipedia
October 31, 2025 - Before the nullish coalescing operator, ... be assigned the value of b if the value of b is truthy, otherwise it will be assigned 3. ... Kotlin uses the ?: operator....
🌐
Baeldung
baeldung.com › home › kotlin › kotlin basics › kotlin elvis operator
Kotlin Elvis Operator | Baeldung on Kotlin
March 19, 2024 - The are several mechanisms that can help to avoid null references in Kotlin. One of them is the Elvis operator. In this short tutorial, we’ll take a look at how this operator works. A question mark followed by a colon represents the Elvis Operator, like this ?:. The name comes from the fact that the operator, seen from the side, resembles an Elvis Presley emoticon with his characteristic hairstyle. Another name for the Elvis operator is the null coalescing operator or null-safety operator.
🌐
DhiWise
dhiwise.com › post › kotlin-elvis-operator-the-key-to-safer-null-proof-code
Kotlin Elvis Operator: The Key to Safer, Null-Proof Code
May 28, 2024 - Understanding this principle allows ... checks. It's a form of null coalescing operator that coalesces multiple lines of potential null-check code into one concise line....
🌐
Medium
medium.com › @jannaynaaraujo › say-goodbye-to-nullpointerexceptions-how-kotlins-null-safety-feature-can-help-you-6fad80d2151b
Say goodbye to NullPointerExceptions! How Kotlin’s Null Safety feature can help you. | by Jannayna Araujo | Medium
November 25, 2023 - The null coalescing operator (?:) is used to simplify handling null values by allowing the definition of a default value that will be used if the expression on the left-hand side of the operator is null.
Find elsewhere
🌐
Scaler
scaler.com › home › topics › elvis operator in kotlin
Elvis Operator in Kotlin - Scaler Topics
December 21, 2023 - The Elvis Operator in Kotlin (null coalescing or null-safety operator) is represented by a question mark and a colon ?:. If it is not null, the operator returns the first expression; if it is, it returns the second expression.
🌐
Reddit
reddit.com › r/programminglanguages › thoughts on the null coalescing (??) operator precedence?
r/ProgrammingLanguages on Reddit: Thoughts on the Null Coalescing (??) operator precedence?
April 30, 2024 -

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:

precoperatorstypes
1Suffixes: a()-> any type
2High-prec arithmetic: a * binteger, integer -> integer
3Low-prec arithmetic: a + binteger, integer -> integer
4Comparisons: a == binteger, integer -> boolean
5Logic: a && bboolean, 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:

  1. What are some reasons for choosing the precedence of ?? other than the ones discussed?

  2. Have any other languages done something different with the precedence, and why?

  3. Has anyone put the precedence of ?? above arithmetic?

Thanks!

Top answer
1 of 11
239

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 is true, 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 be null) 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
2 of 11
173

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

🌐
Medium
medium.com › @guruprasadhegde4 › kotlin-null-safety-99dbc863fcfb
Kotlin Null Safety
November 5, 2024 - Safe Call Operator: The safe call operator checks for null before proceeding with the method call, preventing a NullPointerException. Let Function: The let function allows you to work with the non-null object within its block, reducing the need ...
🌐
GeeksforGeeks
geeksforgeeks.org › kotlin-null-safety
Kotlin Null Safety - GeeksforGeeks
May 10, 2025 - Error:(8, 15) Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String? Here, we can easily assign null to a nullable type variable. But we should use the safe operator to get the length of the string.
🌐
Reddit
reddit.com › r/kotlin › why is there no classic '?:' ternary operator in kotlin?
r/Kotlin on Reddit: Why is there no classic '?:' ternary operator in Kotlin?
May 1, 2024 -

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?

🌐
Koda School
kodaschool.com › blog › understanding-nullability-in-kotlin
Understanding Nullability in Kotlin
Kotlin through its nullability features also provides safe calls which are used to access null values without a crash. Safe calls are made using the safe call operator “ ?.
🌐
Reddit
reddit.com › r/kotlin › do you check for null
r/Kotlin on Reddit: Do you check for null
May 1, 2021 -

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

🌐
Kotlin Discussions
discuss.kotlinlang.org › language design
Different null check behavior in assignment vs expression - Language Design - Kotlin Discussions
June 3, 2021 - Hello! Recently I was having a discussion here about null coalescing operators used on a nullable property, and it brought up some strange behavior with regards to assignments/declarations. (Note: I’ve never had an issue with this in my own code, just an interesting case.) if I set up everything like this, with the goal of using primary.id or else alt.id or else null: class Test(val id: String?
🌐
Android Developers
developer.android.com › codelabs › basic-android-kotlin-compose-nullability
Use nullability in Kotlin | Android Developers
March 22, 2024 - To declare nullable variables in Kotlin, you need to add a ? operator to the end of the type. For example, a String? type can hold either a string or null, whereas a String type can only hold a string. To declare a nullable variable, you need to explicitly add the nullable type.
🌐
The Surve Blog
surve.co.in › home › null coalescing in kotlin and swift
Null Coalescing in Kotlin and Swift - The Surve Blog
March 1, 2024 - Optionals are a powerful source of safety in both Kotlin and Swift, but can also be annoying if you find them littered throughout your code. Nil coalescing operator helps you solve this problem by either unwrapping an optional if it has a value, or providing a default if the optional is empty.
🌐
Tanya Tech Zone
tanyatechzone.com › 2023 › 09 › 15 › null-safety-in-kotlin
Null Safety in Kotlin – Tanya Tech Zone
September 15, 2023 - Kotlin’s null coalescing operator (also known as the “Elvis operator” because of its resemblance to the Elvis Presley’s iconic hairstyle), ensures that a value is not null by providing a default (not null) value.