Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 962
F. Böller Avatar asked Jun 10 '26 02:06

F. Böller


1 Answers

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(); };
  }
}
like image 125
Holger Avatar answered Jun 12 '26 21:06

Holger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!