Search code examples
javafunctional-programmingjava-8functional-interface

Compose Java-8-Functional-Interface


I have an Java-8-FunctionalInterface like this:

@FunctionalInterface
public interface A {
    void doIt ();
}

The Function-Interface provides an compose-Method. I want to use it, to reduce an stream of A like this:

Stream<A> as;
A composed = as.reduce (() -> {}, Function::compose);

As result I want to have a function of A, which calls on each A of the Stream its method doIt.

composed.doIt (); // Executes every doIt ()

But because A is not a implementer of Function, the method reference Function::compose is not possible there. I cannot extend from Function (or Supplier), because then I would have two abstract methods (my own and the one from Function).

What can I do, to make it possible, to compose my functions of A?


Solution

  • There is no reason why the compose method has to come from the Function interface. For your case the Function interface is not appropriate as Function has a return value (rather than void) and it’s compose method is intended to feed the result of one function into the next.

    Just make your own compose method:

    @FunctionalInterface
    public interface A {
      void doIt ();
      default A compose(A next) {
          return () -> { doIt(); next.doIt(); };
      }
    }
    

    Then you can do as intended:

    Stream<A> as=…;
    A composed = as.reduce (() -> {}, A::compose);
    

    Note that since your interface has the same semantic as Runnable you could even make it a sub-interface of Runnable to allow mixing of Runnables and As:

    @FunctionalInterface
    public interface A extends Runnable {
        default void doIt() { run(); }
        default A compose(Runnable next) {
          return () -> { doIt(); next.run(); };
      }
    }