So I'm working with Optionals and came across a strange behaviour. I want to know if this is really an intendet "feature" or something...odd...
Here is the given example: I've got a method with an Optional in whose orElse I want to evaluate an other optional. If the other Optional is not present, I'll raise an IllegalArgumentException:
firstOptionalVar.orElse(secondOptionalVar.orElseThrow(IllegalArgumentException::new));
Now if the secondOptionalVar
is an empty Optional, it will raise an IllegalArgumentException, even if the firstOptionalVar
is Present. This doesn't seem right to me. I would expect it to just raise an IllegalArgumentException if the firstOptionalVar
would not be present.
It's not a big deal to get arround this behavior with java7-methods like:
firstOptionalVar.isPresent() ? firstOptionalVar.get() : secondOptionalVar.orElseThrow(IllegalArgumentException::new);
Has anyone else experienced this behaviour before? Is this really the way optionals should behave?