Home > database >  Is it legal to use `record` as a variable name even though it's a keyword?
Is it legal to use `record` as a variable name even though it's a keyword?

Time:11-13

This came as a surprise: I am able to declare a variable with the name record even though it now has become a keyword. Have a look at this:

public class Main {
    
    static class Foo {
        void bar() { System.out.println("Foo.bar"); }
    }
    
    record R (int a) {}
    
    public static void main(String[] args) {
        Foo record = new Foo();
        record.bar();
        
        R r = new R(5);
        System.out.println(r);
    }
}

When compiled and run with Java 17 this gives:

Foo.bar
R[a=5]

I had expected this to result in an error as is the case when trying to declare a variable named class. As I know the Java guys, they are extremely careful not to break existing code, and so I think this might be a deliberate choice.

(You can't even declare a variable named const because that one const is a keyword in Java.)

CodePudding user response:

Yes, this is legal because record is not a reserved keyword; it is only a contextual keyword.

The Java Language Specification has distinguished between contextual keywords (originally "restricted keywords" and later "restricted identifiers") and reserved keywords since Java 9, due to the introduction of several new keywords in that version. The rationale is given in JLS 9 (§3.9):

A further ten character sequences are restricted keywords: open, module, requires, transitive, exports, opens, to, uses, provides, and with. These character sequences are tokenized as keywords solely where they appear as terminals in the ModuleDeclaration and ModuleDirective productions (§7.7). They are tokenized as identifiers everywhere else, for compatibility with programs written prior to Java SE 9.

Essentially, Foo record = new Foo(); has to be legal in Java 17 because it was legal in earlier versions when record wasn't any kind of keyword, and backwards compatibility is a very high priority for new versions of the Java language.

CodePudding user response:

OK, while looking up const in the JLS again, I saw that record is a contextual keyword whereas const is just a keyword. Contextual keywords are parsed according to context, and when the parser determines that it's not looking at a a record declaration, it will not complain.

  • Related