为什么这个 Java 8 lambda 无法编译? [英] Why does this Java 8 lambda fail to compile?

查看:29
本文介绍了为什么这个 Java 8 lambda 无法编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 Java 代码无法编译:

The following Java code fails to compile:

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

private static void takeBiConsumer(BiConsumer<String, String> bc) { }

public static void main(String[] args) {
    takeBiConsumer((String s1, String s2) -> new String("hi")); // OK
    takeBiConsumer((String s1, String s2) -> "hi"); // Error
}

编译器报告:

Error:(31, 58) java: incompatible types: bad return type in lambda expression
    java.lang.String cannot be converted to void

奇怪的是,标记为OK"的行编译正常,但标记为Error"的行失败.它们看起来基本相同.

The weird thing is that the line marked "OK" compiles fine, but the line marked "Error" fails. They seem essentially identical.

推荐答案

您的 lambda 需要与 BiConsumer 一致.如果您参考 JLS #15.27.3(Lambda 的类型):

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

如果以下所有条件都为真,则 lambda 表达式与函数类型一致:

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

  • [...]
  • 如果函数类型的结果为 void,则 lambda 主体是语句表达式(第 14.8 节)或与 void 兼容的块.

因此 lambda 必须是语句表达式或 void 兼容块:

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.

这篇关于为什么这个 Java 8 lambda 无法编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆