为什么我们不能像组合函数那样组合 Function 和 Consumer?
Function<Integer, String> a = Object::toString;
Consumer<String> b = x -> System.out.println(x);
Consumer<Integer> composed = a.andThen(b);
这似乎是对现有 Function 接口(interface)的明显改进。在 Java 8 中避免使用此功能有什么原因吗?
此外,按如下方式使用 Function 的扩展实现是否是一种常见的做法?
interface FunctionImproved<T, R> extends Function<T, R> {
default Consumer<T> andThen(Consumer<R> consumer) {
return x -> consumer.accept(apply(x));
}
}
最佳答案
andThen
Function<A0, A1>
上的方法实例需要一个 Function<A1, A2>
, 不是 Consumer<A1>
:
a.andThen(string -> {
b.accept(string);
return string;
});
它有一个副作用,因为我们的“消费者”(实际上,它是一个 Function<A1, A1>
)将从之前的 Function<Integer, String> a
返回一个被忽略的值功能。这不是我们想要的。
有一种不同的方式来组成 Function<A0, A1>
和一个 Consumer<A1>
:
Consumer<Integer> c = i -> b.accept(a.apply(i));
可以泛化为实用方法:
<A0, A1> Consumer<A0> functionAndThenConsumer(Function<A0, A1> f, Consumer<A1> c) {
return i -> c.accept(f.apply(i));
}
Is it a common practice to use an extended implementation of
Function
?
有两种选择:
使用静态方法在功能接口(interface)之间进行一些转换(就像我所做的那样)。
使用默认方法扩展这些标准功能接口(interface)(就像您所做的那样)。只要选择一个正确有意义的名字,而不是像
FunctionImproved
.
关于java - 如何在 Java 8 中组合 Function<T, R> 和 Consumer<R>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47519979/