撰写Java-8-Functional-Interface

F. *_*ler 2 java functional-programming java-8 functional-interface

我有一个像这样的Java-8-FunctionalInterface:

@FunctionalInterface
public interface A {
    void doIt ();
}
Run Code Online (Sandbox Code Playgroud)

Function-Interface提供的compose-方法.我想用它来减少这样的流A:

Stream<A> as;
A composed = as.reduce (() -> {}, Function::compose);
Run Code Online (Sandbox Code Playgroud)

结果我希望有一个函数A,它调用每个AStream的方法doIt.

composed.doIt (); // Executes every doIt ()
Run Code Online (Sandbox Code Playgroud)

但由于A 不是实现者Function,因此Function::compose不可能使用方法参考.我不能从Function(或Supplier)扩展,因为那时我将有两个抽象方法(我自己和来自Function).

我能做些什么来使我的功能成为可能A呢?

Hol*_*ger 7

没有理由为什么该compose方法必须来自Function接口.对于您的情况,Function接口不适合Function具有返回值(而不是void),并且它的compose方法旨在将一个函数的结果提供给下一个.

只需制作自己的compose方法:

@FunctionalInterface
public interface A {
  void doIt ();
  default A compose(A next) {
      return () -> { doIt(); next.doIt(); };
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以按预期做:

Stream<A> as=…;
A composed = as.reduce (() -> {}, A::compose);
Run Code Online (Sandbox Code Playgroud)

请注意,由于您的界面具有相同的语义,Runnable甚至可以使其成为Runnable允许混合Runnables和As 的子界面:

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