Java 22 模式匹配不适用于记录模式匹配。给出编译问题

问题描述 投票:0回答:1

尝试使用Java 22的功能。下面是代码,但正在编译。

    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

即使以下面的方式使用上面的代码,它也能工作

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

这里的 Employee 是一条记录。我正在使用java 22。

无法理解这里出了什么问题

java java-22
1个回答
0
投票

未命名模式是用一个下划线(

_
)字符编写的,但在您的代码中您编写了2个下划线,因此解析器无法理解您在这里尝试执行的操作。

使用

int __
(两个下划线)是有效的,因为
__
是一个有效的 Java 标识符。您没有使用未命名模式 - 您只是将第二个记录组件绑定到名为
__
的局部变量,就像
int x
这里将第一个记录组件绑定到名为
x
的局部变量一样。

与未命名模式不同,您可以像常规局部变量一样使用

__

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
}
© www.soinside.com 2019 - 2024. All rights reserved.