尝试使用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。
无法理解这里出了什么问题
未命名模式是用一个单下划线(
_
)字符编写的,但在您的代码中您编写了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
}