MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/java/comments/1r7iv5p/objectsrequirenonnullelse/o60g17k/?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
Show parent comment
4
No one seems to be mentioning the new form that got unlocked with the recent instanceOf improvements
City city = from.getCity() instanceOf City city ? city : defaultCity;
I don't have a preference between this (instanceOf) and the OP's pattern (Objects.requireNonNullElse)
but both of those feel better than repeating from.getCity() twice.
View all comments
Show parent comment
4
u/noswag15 Feb 18 '26
No one seems to be mentioning the new form that got unlocked with the recent instanceOf improvements
City city = from.getCity() instanceOf City city ? city : defaultCity;
I don't have a preference between this (instanceOf) and the OP's pattern (Objects.requireNonNullElse)
but both of those feel better than repeating from.getCity() twice.