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

'variable may not have been initialized' error for parameter in lambda function

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 9
    • 8u40, 9
    • tools
    • b68
    • x86
    • linux
    • Verified

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

        ADDITIONAL OS VERSION INFORMATION :
        Linux dev 3.11.0-12-generic #19-Ubuntu SMP Wed Oct 9 16:20:46 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux


        A DESCRIPTION OF THE PROBLEM :
        When a return statement exists in a constructor, and a parameterized lambda is defined at the class level, javac throws an error stating 'variable ___ might not have been initialized' for the parameter passed into the lambda. The error is thrown at the return statement, where the parameter in question is out of scope.

        For example, running javac against this code snippet:

        public class Main {

            Predicate<String> predicate = var -> var.isEmpty();

            Main() {
                return;
            }
        }

        produces the error:
        Error:(8, 9) java: variable var might not have been initialized

        Replacing the lambda expression with an anonymous declaration (as below) eliminates the compiler error:

        Predicate<String> predicate = new Predicate<String>() {
                    @Override
                    public boolean test(String s) {
                        return s.isEmpty();
                    }
                };

        STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
        Try compiling the provided executable test case.


        REPRODUCIBILITY :
        This bug can be reproduced always.

        ---------- BEGIN SOURCE ----------
        public class JavacBugMain {

            public static void main(String[] args) {
                new Inner();
            }

            private static class Inner {
                Predicate<String> synonymComparator = a -> a.isEmpty();

                Inner() {
                    if (true) {
                        return;
                    }

                    synonymComparator.test("");
                }
            }
        }
        ---------- END SOURCE ----------

        CUSTOMER SUBMITTED WORKAROUND :
        Convert the lambda expression to an anonymous class.

              sadayapalam Srikanth Adayapalam (Inactive)
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              6 Start watching this issue

                Created:
                Updated:
                Resolved: