I have been trying to figure why some decisions have been made regarding the design of java.util.Optional. The issues I had with it were:
I felt it's inelegant that java would wrap Optional instances in additional Optionals. I would expect a clean api to automatically handle values of type optional without boxing them again.. i.e, Optional.of(Optional.of("name")) would ideally have type Optional<String> instead of Optional<Optional<String>>.
flatMap felt unnecessary.. why not just provide another overload of map?..
public <U> Optional<U> map(Function<? super T, ? extends Optional<? extends U>> mapper) { // ... same implementation as flatMap }
So you would not need to worry about picking between flatMap and the regular map, the appropriate one would be automatically picked according to your mapper.
- if the whole point of Optional is to streamline your code then why does get() throw an Exception if no value is present?.. how is this cleaner than simply returning null. Especially since we also have orElseThrow() that does exactly the same.
P.S - My assumption was that there's no good reason to box a value in more than one layer of Optional, so if there are cases where this makes sense I'd love to know.
Does anyone have insights on that? Thanks