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

查看:2422
本文介绍了为什么这个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< String,String> 。如果您参考 JLS#15.27.3(类型a 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,表达式(§14.8)或与空格兼容的块。

语句表达式或void兼容块:

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


  • 构造函数调用是语句表达式,以便它编译。<​​/ li>
  • 字符串文字不是语句表达式并且不与空间兼容(参见

  • 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天全站免登陆