r/learnjava • • 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

12 comments sorted by

View all comments

Show parent comment

1

u/silverscrub Feb 20 '26

Isn't it the other way around? Java null is JS undefined, although TS undefined is a better example.

I don't actually code in Java much, but in Scala. We have:

  • null: when interoping with Java code
  • nothing: a type that can't exist
  • nil: an empty linked list
  • none: an empty optional
  • void: although it's called Unit or ()

They all serve important purposes for type safety. I wouldn't want ADTs that blend together. Maybe that's where Optional fails in Java. In Scala, I literally never check for null, but that only works because it's consistent with returning optional values when applicable. In Java, optional isn't used consistently, so you can't trust methods that return non-optional objects.