public class CurringTest {
public static void main(String[] args) {
IntFunction<Integer> currPrice = curring(items ->
Long.valueOf(items.stream()
.mapToLong(i -> Long.valueOf(i))
.sum())
.intValue()
);
currPrice.apply(1);
currPrice.apply(2);
int result = currPrice.apply(Integer.MAX_VALUE);
System.out.println(result);
}
public static IntFunction<Integer> curring(Function<List<Integer>, Integer> fn) {
final List<Integer> result = new ArrayList<>();
return arg -> {
if (arg != Integer.MAX_VALUE) {
result.add(arg);
} else {
//当输入INT最大值时进行计算
return fn.apply(result);
}
return null;
};
}
}
输出结果是3,我想知道result作为一个局部变量是如何保存值的。
这个类似于JS的闭包概念,curring()在执行完毕之后,其活动对象也不会被销毁,因为匿名函数的作用域链仍然在引用这个活动对象。换句话说,当curring()函数返回后,其执行环境的作用域链会被销毁,但它的活动对象仍然会留在内存中,直到匿名函数被销毁后,curring()的活动对象才会被销毁