在java中记录模式,无需instanceof或swtich

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

Java 21 记录模式承诺在 Java 语言中引入解构。然而,它似乎与模式匹配紧密耦合,只能用作

instanceof
比较的一部分或在
switch
语句/表达式中。

考虑以下记录。

public record Point(int x, int y) {}

有没有一种方法可以在不使用

instanceof
switch
的情况下解构该特定类型的对象?以下尝试确实会破坏
point
。但这段代码没有什么意义,因为如果我们假设空安全,
instanceof
switch
都不是不必要的。

Point point = new Point(0, 0);

// destructuring with instanceof
if (point instanceof Point(int x, int y)) {
    System.out.printf("Point at (%d,%d)", x, y);
}

// destructuring with switch
switch (point) {
    case Point(int x, int y) -> System.out.printf("Point at (%d,%d)", x, y);
}

感谢您的见解。

java pattern-matching java-21 record-patterns
1个回答
0
投票

不。正如您在发布的 JEP 中看到的,他们正在执行“无用的”instanceof 检查,这些检查保证是真实的,目的是解构。

static void printColorOfUpperLeftPoint(Rectangle r) {
    if (r instanceof Rectangle(ColoredPoint(Point p, Color c))

这里,

r
肯定是一个矩形,但是模式匹配语法要求你无论如何都要检查它。

© www.soinside.com 2019 - 2024. All rights reserved.