I've been working with the new Optional type in Java 8, and I've come across what seems like a common operation that isn't supported functionally: an "orElseOptional"
Consider the following pattern:
Optional<Result> resultFromServiceA = serviceA(args);
if (resultFromServiceA.isPresent) return result;
else {
Optional<Result> resultFromServiceB = serviceB(args);
if (resultFromServiceB.isPresent) return resultFromServiceB;
else return serviceC(args);
}
There are many forms of this pattern, but it boils down to wanting an "orElse" on an optional that takes a function producing a new optional, called only if the current one does not exist.
It's implementation would look like this:
public Optional<T> orElse(Supplier<Optional<? extends T>> otherSupplier) {
return value != null ? this : other.get();
}
I'm curious if there's a reason such a method doesn't exist, if I'm just using Optional in an unintended way, and what other ways people have come up with to deal with this case.
I should say that I think that solutions involving custom utility classes/methods aren't elegant because people working with my code won't necessarily know they exist.
Also, if anyone knows, will such a method be included in JDK 9, and where might I propose such a method? This seems like a pretty glaring omission to the API to me.
This is part of JDK 9 in the form of method or
, which takes a Supplier<Optional<T>>
. Your example would then be:
return serviceA(args)
.or(() -> serviceB(args))
.or(() -> serviceC(args));
For details see the Javadoc, this post I wrote, or ticket JDK-8080418 where this method was introduced.