Why does this Java 8 lambda fail to compile?

后端 未结 4 1761
花落未央
花落未央 2020-12-08 06:16

The following Java code fails to compile:

@FunctionalInterface
private interface BiConsumer {
    void accept(A a, B b);
}

private static void t         


        
4条回答
  •  旧时难觅i
    2020-12-08 07:09

    Your lambda needs to be congruent with BiConsumer. If you refer to JLS #15.27.3 (Type of a Lambda):

    A lambda expression is congruent with a function type if all of the following are true:

    • [...]
    • If the function type's result is void, the lambda body is either a statement expression (§14.8) or a void-compatible block.

    So the lambda must either be a statement expression or a void compatible block:

    • A constructor invocation is a statement expression so it compiles.
    • A string literal isn't a statement expression and is not void compatible (cf. the examples in 15.27.2) so it does not compile.

提交回复
热议问题