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

Compiler should accept final variable in Record Pattern

XMLWordPrintable

    • b27
    • generic
    • generic

        ADDITIONAL SYSTEM INFORMATION :
        javac 22-ea, javac 21.0.1

        A DESCRIPTION OF THE PROBLEM :
        This does not compile:

        {code:java}
        public class WithFinal {
        record ARecord(String aComponent) {}

        public String match(Object o) {
        return switch(o) {
        case ARecord(final String s) -> s;
        default -> "No match";
        };
        }
        }
        {code}

        javac outputs the following errors:

        {noformat}
        ./WithFinal.java:6: error: illegal start of expression
        case ARecord(final String s) -> s;
        ^
        ./WithFinal.java:6: error: ';' expected
        case ARecord(final String s) -> s;
        ^
        ./WithFinal.java:6: error: not a statement
        case ARecord(final String s) -> s;
        ^
        3 errors
        {noformat}

        According to chapter 14.30.1. of the JLS, {{final}} is allowed as a _VariableModifier_. Without {{final}}, mutating the pattern variable is valid:

        {code:java}
        public class NotEffectivelyFinal {
        record ARecord(String aComponent) {}

        public String match(Object o) {
        return switch(o) {
        case ARecord(String s) -> {
        s = "";
        yield s;
        }
        default -> "No match";
        };
        }
        }
        {code}


              abimpoudis Angelos Bimpoudis
              webbuggrp Webbug Group
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Created:
                Updated:
                Resolved: