r/learnjava • 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;
}
8
Upvotes
View all comments
Show parent comment
1
u/silverscrub Feb 19 '26
Makes sense for method parameters to some degree. Passing optional parameters expands the scope of the method.
As for using it as a variable type or return type, I don't understand how using null is any better. Especially when two or more nullable values depend on each other.