Is it possible to do something similar to the following code in Java
int y = x ?? -1;
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.
Integer
because an int
cannot be compared to null
. –
Devour code blocks
are for so you can tell that int?
is a data type, not a question. :) –
Hulsey int y = x ?? -1
, x is evaluated once. –
Renny 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.
firstNonNull
fails if the second argument is null to help programmer errors be caught faster. –
Stimulative Objects.firstNonNull
, any functions you have passed will be evaluated. This makes it potentially far more computationally expensive than C#'s ??
. –
Mastoid Short answer: no
The best you can do is to create a static utility method (so that it can be imported using import static
syntax)
public static <T> T coalesce(T one, T two)
{
return one != null ? one : two;
}
The above is equivalent to Guava's method firstNonNull
by @ColinD, but that can be extended more in general
public static <T> T coalesce(T... params)
{
for (T param : params)
if (param != null)
return param;
return null;
}
Possible heap pollution from parameterized vararg type
warning when using the second one. –
Gwyngwyneth ObjectUtils.firstNonNull(T...)
from Apache Commons Lang 3 is another option. I prefer this because, unlike Guava, this method does not throw an Exception
. It will simply return null
.
No, and be aware that workaround functions are not exactly the same, a true null coalescing operator short circuits like && and || do, meaning it will only attempt to evaluate the second expression if the first is null.
© 2022 - 2024 — McMap. All rights reserved.
Nullable<int> x;
orint? x
. if x is just int, its a compilation failure. – NonmetallicObjects.coalesce(...)
or equivalent. – HelainadefaultObj
must be non-null. Also sad that it's namedrequire...
because it makes it sound like it's going to throw if the parameter is null, in reality it just returns the default object passed in. Poor naming. Should have beencoalesce
or similar. – Helaina