我有一个像这样的Java-8-FunctionalInterface:
@FunctionalInterface
public interface A {
void doIt ();
}Function-Interface提供了一个compose-Method。我想使用它来减少这样的A流:
Stream<A> as;
A composed = as.reduce (() -> {}, Function::compose);因此,我希望有一个A函数,它调用流的每个A --它的方法doIt。
composed.doIt (); // Executes every doIt ()但是由于不是Function的实现者,所以方法引用Function::compose是不可能的。我不能从Function (或Supplier)扩展,因为这样我就有两个抽象方法(我自己的和Function的)。
我能做什么,使它成为可能,组成我的A功能
发布于 2014-06-04 13:54:27
没有理由compose方法必须来自Function接口。对于您的情况,Function接口是不合适的,因为Function有一个返回值(而不是void),它的compose方法的目的是将一个函数的结果输入下一个函数。
只需创建您自己的compose方法:
@FunctionalInterface
public interface A {
void doIt ();
default A compose(A next) {
return () -> { doIt(); next.doIt(); };
}
}然后你就可以按计划做:
Stream<A> as=…;
A composed = as.reduce (() -> {}, A::compose);请注意,由于您的接口具有与Runnable相同的语义,您甚至可以使它成为Runnable的子接口,从而允许混合Runnables和As:
@FunctionalInterface
public interface A extends Runnable {
default void doIt() { run(); }
default A compose(Runnable next) {
return () -> { doIt(); next.run(); };
}
}https://stackoverflow.com/questions/24038947
复制相似问题