Optional.orElseChain ?

Remi Forax forax at univ-mlv.fr
Fri Apr 17 21:37:49 UTC 2015

Hi guys,
I was trying to write a code that uses Optional and I think one method 
is missing.

Let suppose I want to load a type (like a class, an interface, etc) that 
can come
either by reflection, or by using ASM.
I will write an interface TypeProvider that is able to load a Type and
i will chain the different type providers like this:

   TypeProvider asmTypeProvider = ...
   TypeProvider reflectionTypeProvider = ...
   TypeProvider provider =

so I've implemented TypeProvider like this:

public interface TypeProvider {
   public Optional<Type> loadType(String name);

   public default TypeProvider chain(TypeProvider provider) {
     return name -> {
       Optional<Type> type = loadType(name);
       return type.isPresent()? type: provider.loadType(name);

   public default TypeProvider orFail() {
     return chain(fail());

   public static TypeProvider fail() {
     return name -> Optional.empty();

As you can see the code is not bad but the code of chain() could be 
if there was a way on Optional to call a Supplier of Optional if an 
Optional is empty.
Currently, orElse() takes a value, orElseGet takes a lambda that will 
return a value
and there is no method that takes a lambda and return an Optional
(like flatMap but but with a supplier that will be called if the 
Optional is empty).

If we add the method orElseChain(Supplier<? extends Optional<T>> supplier)
perhaps with a better name ?, then the code of chain is better:

   public default TypeProvider chain(TypeProvider provider) {
     return name -> loadType(name).orElseChain(() -> 

Am i the only one to think that this method is missing ?


More information about the core-libs-dev mailing list