javajava-22

Java 22 pattern matching not working with record pattern matching. Giving compilation issue


Trying to use feature of Java 22. Below is the code but getting compilation.

    Employee emp= new Employee(2, 3);
    
    if (emp instanceof Employee(int x, __)) {
          System.out.println("Employee is a position, x = " + x);
    }

    Compilation exception is: Syntax error, insert "RecordStructurePattern" to complete RecordPattern

Even If used above code in below way then its working

    Employee emp= new Employee(2, 3);
    
    if (emp instanceof Employee(int x, int __)) {
          System.out.println("Employee is a position, x = " + x);
    }

Here Employee is a record. I am using java 22.

Not able to understand what is wrong here


Solution

  • The unnamed pattern is written with a single underscore (_) character, but in your code you have written 2 underscores, so the parser doesn't understand what you are trying to do here.

    Using int __ (two underscores) works, because __ is a valid Java identifier. You are not using the unnamed pattern - you are just binding the second record component to a local variable called __, in the same way that int x here binds the first record component to a local variable called x.

    Unlike an unnamed pattern, you can use __ like a regular local variable.

    if (emp instanceof Employee(int _, int __)) {
        System.out.println(__); // this compiles
        System.out.println(_); // this doesn't compile because "_" is not the name of a variable
    }