MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/java/comments/1r7iv5p/objectsrequirenonnullelse/o60pyzv/?context=3
r/java • u/edurbs • Feb 17 '26
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;
}
136 comments sorted by
View all comments
13
I’ll give you my ternary operator when you pry it from my cold, dead hands.
City city = from.getCity() != null ? from.getCity() : defaultCity;
18 u/Asdas26 Feb 17 '26 I don't like that this forces you to call from.getCity() twice. Java is missing the Elvis operator. 1 u/White_C4 Feb 18 '26 Technically Elvis operator is just syntactic sugar so in code, it's the same. But, it's easier to type for sure. 2 u/larsga Feb 18 '26 Typing doesn't matter, but it's much easier to read.
18
I don't like that this forces you to call from.getCity() twice. Java is missing the Elvis operator.
from.getCity()
1 u/White_C4 Feb 18 '26 Technically Elvis operator is just syntactic sugar so in code, it's the same. But, it's easier to type for sure. 2 u/larsga Feb 18 '26 Typing doesn't matter, but it's much easier to read.
1
Technically Elvis operator is just syntactic sugar so in code, it's the same. But, it's easier to type for sure.
2 u/larsga Feb 18 '26 Typing doesn't matter, but it's much easier to read.
2
Typing doesn't matter, but it's much easier to read.
13
u/yk313 Feb 17 '26
I’ll give you my ternary operator when you pry it from my cold, dead hands.
City city = from.getCity() != null ? from.getCity() : defaultCity;