Java.util.function.Function
中的默认方法
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
main
Function<Integer, Integer> doubleFunction = x -> x * 2;
Function<Integer, Integer> squareFunction = x -> x * x;
int result1 = doubleFunction.apply(5); // 10
int result2 = squareFunction.apply(5); // 25
Function<Integer, Integer> integerIntegerFunction = doubleFunction.andThen(squareFunction);
int result3 = doubleFunction.andThen(squareFunction).apply(5); // 100
int result4 = doubleFunction.compose(squareFunction).apply(5); // 50
问题:语句-
doubleFunction.compose(squareFunction).apply(5)
,doubleFunction.compose
返回(V v) -> apply(before.apply(v))
,外层代码apply(...)
如何运行?
before.apply(v)
返回 int 数字,假设返回符号 res。对于(V v) -> apply(res)
,这怎么能看做是doubleFunction的实例化调用。【池英语,sry】
Function.compose
采用 lambda 作为参数,并在默认方法中将其分配给 before
。
那么。
int result4 = doubleFunction.compose(squareFunction).apply(5);
System.out.println(result4);
与
相同Function<Integer, Integer> before = squareFunction;
int result4 = doubleFunction.apply(before.apply(5));
System.out.println(result4);
所以首先将
5
平方得到 25
,然后将其加倍得到 50
。