为什么带有显式返回的空lambda和构造函数会导致编译器错误(Java Bug?) [英] Why does an empty lambda and constructor with an explicit return cause a compiler error (Java Bug?)

查看:101
本文介绍了为什么带有显式返回的空lambda和构造函数会导致编译器错误(Java Bug?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可重现的测试用例:

I have a reproducible test case:

public class TestCase {

    private final java.util.function.Consumer<Object> emptyCallback = result -> {};

    public TestCase() {
        return;
    }

    public static void main(String... args) {
        new TestCase();
    }
}

使用Java 8,更新51(Oracle JDK)。使用IntelliJ和javac都无法编译。

Using Java 8, update 51 (Oracle JDK). This can't be compiled, using both IntelliJ and javac.

IntelliJ输出:

IntelliJ output:

Error(6, 7): java: variable result might not have been initialized

javac输出:

TestCase.java:6: error: Variable result might not have been initialized
        return;
        ^
1 error

现在奇怪的是,删除 return; Consumer 将修复错误。这是一个java bug,还是我在这里缺少一些语言设计?

Now what is strange, is that removing return; or the Consumer will fix the error. Is this a java bug, or is there something of the language design that I am missing here?

编辑:这不是构造函数如何返回值,这实际上是一个构造函数,而不是关于构造函数的返回值,但是变量初始化。

This is not a duplicate of How can a constructor return a value, this is actually a constructor and isn't about the return value of constructor but variable initialization.

推荐答案

你可以找到官方的错误报告这里。该问题已在Java 9中修复。

You can find an official bug report here. The issue is fixed in Java 9.

你可以在构造函数中返回


return语句将控制返回给方法的调用者(§8.4,$ b $b§15.12)或构造函数(§8.8,§15.9) )。

A return statement returns control to the invoker of a method (§8.4, §15.12) or constructor (§8.8, §15.9).

这篇关于为什么带有显式返回的空lambda和构造函数会导致编译器错误(Java Bug?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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