我一直在尝试用一而在Java函数式编程,并发现我开始喜欢使用的@FunctionalInterface从功能java.util.function包,如功能,BiFunctions,UnaryOperators,谓语,BiPredicates等代替简单的私有方法我类。我知道他们的应用程序更推荐作为参数传递给另一个函数,这就是我通常倾向于使用它们的方式,但我现在只是发现它们立即并且以某种方式更好。
事实上,我现在倾向于将其中一些声明为变量,然后在需要时在我的类中使用。
我似乎没有找到任何使用这些而不是简单方法的指南或缺点。
那么:以这种方式使用它们有什么缺点吗?
为什么更喜欢:
private boolean foo(final int a, final int b){
return a < b;
}
Run Code Online (Sandbox Code Playgroud)
代替:
private final BiPredicate<Integer,Integer> foo = (a,b) -> a < b;
Run Code Online (Sandbox Code Playgroud)
我在最近的项目中如何使用它们的一个例子:
private final BiFunction<BoardPosition, Pair<Integer, Integer>, BoardPosition> sumBoardPosWithPair = (pos,
pair) -> new BoardPositionImpl(pos.getX() + pair.getX(), pos.getY() + pair.getY());
private final Function<Pair<Integer, Integer>, UnaryOperator<BoardPosition>> unaryCreator = (
axis) -> (p) -> this.sumBoardPosWithPair.apply(p, axis);
/**
* If you need to call the fromFunction method twice for specular …Run Code Online (Sandbox Code Playgroud)