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/vegan_antitheist Feb 20 '26
Well, it depends. When something isn't defined the compilern would complain in Java. Map.prototype.get() returns undefined if there is no corresponding value for the give key. In Java, Map.get is way older than Optional. A Scala Map gives you an Option. An empty set of types only exists for languages that treat types as sets. I don't know if Scala calls this nothing. Never in TS is that for when it shouldn't reach the point where there is nothing to return but the function should return something or when it's an infinite loop. "void" is even less that empty set because it simply doesn't return anything. Unit is just something to return that holds no value.