Java:使用lambda而不将其分配给变量

时间:2019-03-03 15:53:15

标签: java lambda

我正在像这样使用lambda:

TwoValueCommand addition = (a, b) -> a + b;
return pushTwoValueCommand(addition);

有没有办法这样写:

return pushTwoValueCommand(TwoValueCommand (a, b) -> a + b);

无需创建变量?

编辑

这些问题的答案:

How to initialize field using lambda

Assign result of Java lambda to field

为我指明了正确的方向,但是无论如何,他们的用词差异都很大。

3 个答案:

答案 0 :(得分:5)

根据How to initialize field using lambda,我确定可以做到这一点:

return pushTwoValueCommand((TwoValueCommand) (a, b) -> a + b); // put parentheses around type to cast lambda expression

从@ernest_k看,我也可以这样做:

return pushTwoValueCommand((a, b) -> a + b);

(尽管我不了解该版本的工作原理-不必使用功能性的接口吗?https://medium.freecodecamp.org/learn-these-4-things-and-working-with-lambda-expressions-b0ab36e0fffc

编辑

@AndrewTobilko的答案很好地解释了为什么可以执行此操作(无需强制转换)。可以从pushTwoValueCommand的方法定义中推断类型,只要不使pushTwoValueCommand重载(pushTwoValueCommand的多个定义),编译器就无法确定要使用哪个函数接口。

答案 1 :(得分:2)

问题在于没有上下文的(a, b) -> a + b模棱两可。可以是BinaryOperator<Integer>BiFunction<Integer, Integer, Integer>TwoValueCommand。它也可以表示定义了C method(A, B)之类方法的任何其他功能接口。

如果pushTwoValueCommand重载了相互冲突的功能接口,则会遇到上述模棱两可的问题。

如果pushTwoValueCommand有一个版本,则可以直接传递(a, b) -> a + b,就可以了。

答案 2 :(得分:1)

另一种方法是使pushTwoValueCommand方法能够接受功能接口
对于此特定用例,BiFunctiondocumentation)是理想的。您的代码可以改写为

<T> T pushTwoValueCommand(
        final BiFunction<T, T, T> function,
        final T right,
        final T left) {
    // Do something else, and then
    return function.apply(right, left);
}

并用作

return pushTwoValueCommand((a, b) -> a + b, 1, 3);
相关问题