Search code examples
javagenericsreflectionfunctional-interface

Functional Interface accepting Stream or Optional?


I want to create a @FunctionalInterface in Java which accepts both Streams or Optional types as a parameter. I tried to do this, but since they don't share a common interface it seems impossible to achieve. I also tried using a common wrapper class which invokes the @FunctionalInterface but since I need the type parameters at runtime it seems this isn't possible.

Minimum example:

@FunctionalInterface
public interface AcceptingInterface<S, T> {

    T accept(S s);

}

public class Test<S, T> {

    private final AcceptingInterface<S, T> funcInterface;

    private final Class<S> source;

    private final Class<T> target;

    public Test(AcceptingInterface<S, T> a, Class<S> s, Class<T> t) {
        this.funcInterface = a;
        this.source = s;
        this.target = t;
    }

    public T invoke(S s) {
        return s == null ? null : this.funcInterface.accept(s);
    }

    public Class<S> getSource() {
        return source;
    }

    public Class<T> getTarget() {
        return target;
    }
}

Maybe my approach is wrong... I would love to receive feedback and/or a solution to this problem.


Solution

  • I assume you want to treat an Optional as a Stream of 0-1 elements, in which case you can add a default method that translates from Optional to Stream, thusly:

    @FunctionalInterface
    public interface AcceptingInterface<V, T> {
    
        T accept(Stream<? extends V> s); 
        default T accept(Optional<? extends V> opt){
            return accept(opt.map(Stream::of).orElseGet(Stream::empty)); 
        }
    
    }
    

    Java 9 is supposed to add an Optional.stream() method.