Sadly - no. The closest you can do is:
int y = (x != null) ? x : -1;
Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available.
Answer from Andrzej Doyle on Stack OverflowSadly - no. The closest you can do is:
int y = (x != null) ? x : -1;
Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available.
The Guava library has a method that does something similar called MoreObjects.firstNonNull(T,T).
Integer x = ...
int y = MoreObjects.firstNonNull(x, -1);
This is more helpful when you have something like
int y = firstNonNull(calculateNullableValue(), -1);
since it saves you from either calling the potentially expensive method twice or declaring a local variable in your code to reference twice.
Sadly - no. The closest you can do is:
int y = (x != null) ? x : -1;
Of course, you can wrap this up in library methods if you feel the need to (it's unlikely to cut down on length much), but at the syntax level there isn't anything more succinct available.
Answer from Andrzej Doyle on Stack OverflowMany 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!
Checking for null is quite verbose in Java. The current best practice is to either use Nullability annotations or Optional<T>. Personally, I'm in the annotations camp. Yes, optional is very useful in streams but I don't like the cognitive and runtime overhead it implies anywhere else.
My dream would be if one day nullability would be added to the type system. Obviously, that's a lot of work. But wouldn't be a pragmatic first step, to reduce just the boilerplate of null checks with a safe call operator? The compiler could surely rewrite this code:
if (getLoggedInUser()?.isPowerUser()) {
}To this:
if (getLoggedInUser() != null && getLoggedInUser().isPowerUser()) {
}To avoid an unexpected double method invocation, it could assign to ad hoc created temp variables:
User generatedSafeCall1;
if ((generatedSafeCall1 = getLoggedInUser()) != null && generatedSafeCall1.isPowerUser()) {
}
I believe this would end a lot of complaints about null handling in Java. Since only new code would use the ?. operator, backwards compatibility shouldn't be an issue either. Are there any downsides that I'm missing?