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

2

u/vegan_antitheist Feb 19 '26

Optional is basically like undefined in JS.
It's just another way to say that there isn't anything.
But since "null" is used as a value, it's still something. When you get an empty optional it's actually "nothing".
But JS also has "empty" for when an array doesn't have any value at some index (not even null or undefined), so Java is not quite there yet.
Someday we will have null, nil, nothing, none, empty, undefined, void, (), [], {}, ∅, and a bunch of other ways do say that there is nothing. And don't forget NaN for when a number is not a number.

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.

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.