13

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.

Community
  • 1
  • 1
Rogue
  • 11,105
  • 5
  • 45
  • 71
  • Possible duplicate of [Java: How can a constructor return a value?](http://stackoverflow.com/questions/2574276/java-how-can-a-constructor-return-a-value) – OneCricketeer Jul 27 '16 at 22:15
  • 4
    Why would you `return` from a constructor? – Elliott Frisch Jul 27 '16 at 22:16
  • @ElliottFrisch this is a very watered down reproducible example from a different issue,where upon calling System#exit the constructor should have ceased immediately. – Rogue Jul 27 '16 at 22:17
  • I see your edit, and unless Java 8 has this feature and I am not aware, you simply can't return from a Constructor – OneCricketeer Jul 27 '16 at 22:20
  • @cricket_007 sure you can, just as long as there isn't a field with a lambda (according to the bug report below). `return` has always been supported in the constructor. – Rogue Jul 27 '16 at 22:24
  • I see... I suppose the JLS link below clarifies that – OneCricketeer Jul 27 '16 at 22:27

1 Answers1

12

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).

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    Seems like it's known, so at least I don't have to write up a massive bug report on oracle. Yay! – Rogue Jul 27 '16 at 22:24