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

Spurious "variable might not have been initialized" with sealed class switch

XMLWordPrintable

    • b10
    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      The preview pattern matching compiler feature in JDK 17 is not correctly recognizing that a variable is initialized unless a default case is added (which completely defeats the purpose of using the new switch statements). See the provided source code for more details.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Attempt to compile the sample code using the '--enable-preview' option

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The code should compile without errors.
      ACTUAL -
      javac -source 17 --enable-preview Example.java
      Sample.java:18: error: variable description might not have been initialized
              return description;
                     ^
      Note: Sample.java uses preview features of Java SE 17.
      Note: Recompile with -Xlint:preview for details.
      1 error

      ---------- BEGIN SOURCE ----------
      class Example
      {
          sealed interface MyBoolean
          {
              record True() implements MyBoolean {}
              record False() implements MyBoolean {}
          }

          String describe(MyBoolean value)
          {
              final String description;

              switch (value) {
                  case MyBoolean.True t -> description = "It's True";
                  case MyBoolean.False f -> description = "It's False";
                  //default -> throw new IllegalStateException("Cannot happen javac!");
              }

              return description;
          }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      You either must include a default statement or initialize the variable to some value (making it non-final), neither of which are acceptable.

            jlahoda Jan Lahoda
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated:
              Resolved: