Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an empty lambda and constructor with an explicit return cause a compiler error (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();
    }
}

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

IntelliJ output:

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

javac output:

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

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?

Edit: 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.

like image 295
Rogue Avatar asked Jul 27 '16 22:07

Rogue


1 Answers

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


You can return inside a constructor

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

like image 69
3 revs Avatar answered Oct 23 '22 07:10

3 revs