Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8166115

'return' in constructor with a lambda assigned to a class field

XMLWordPrintable

    • x86

      FULL PRODUCT VERSION :
      java version "1.8.0_101"
      Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
      Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows [Version 10.0.10586]

      A DESCRIPTION OF THE PROBLEM :
      The given source code fails to compile even though it is completely valid source code according to the Java Language Specification (JLS). The JLS 1.8 states explicitly: "A return statement (§14.17) may be used in the body of a constructor if it does not include an expression." (ref. docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8 section 8.8.7)

      If the 'return' is removed from the constructor then the source compiles.
      If the lambda statement is removed then the source compiles.

      The combination of a 'return' in the constructor and a lambda assigned to a class field causes the source to fail to compile.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Try to compile the given source code.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The source code to compile successfully, without errors.
      ACTUAL -
      The code does not compile and produces this error:

      UnsolvableClass.java:10: error: variable theErrorVariable might not have been initialized
              return;
              ^
      1 error

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      UnsolvableClass.java:10: error: variable theErrorVariable might not have been initialized
              return;
              ^
      1 error

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      import java.util.function.Consumer;

      public class UnsolvableClass {

          private Consumer<Object> func = (Object theErrorVariable) -> {};

          public UnsolvableClass() {
              return;
          }

      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Do not use any 'return' statements in the constructor.
      Or don't use lambdas.

            fmatte Fairoz Matte
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: