r/java • u/edurbs • Feb 17 '26
Objects.requireNonNullElse
I must have been living in a cave. I just discovered that this exists.
I can code
City city = Objects.requireNonNullElse(form.getCity(), defaultCity);
... instead of:
City city = form.getCity();
if(city == null){
city = defaultCity;
}
113
Upvotes
View all comments
Show parent comment
0
u/hwaite Feb 18 '26
Every decision results from a multi-factor cost/benefit analysis; the Elvis operator is just another line item. Still, calling it "basic syntactic sugar" understates the value proposition.
Optionalusage is inconsistent in Java because (a) it's unwieldy and (b) it wasn't baked into the language from the beginning. The lack of universal adoption means you can never really be sure if an expression is nullable. Even if something is declared as Optional, some psychopath might return null. I don't expect anyone to switch languages just for first-class null handling. That doesn't mean it's not worth mentioning the Kotlin approach. "The more you know..."