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

问题描述 投票: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个回答
1
投票

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

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

这里,

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

您正在寻找的功能在 JavaScript 世界中称为“解构赋值”。

const point = { x: 1, y: 2 };
const { x, y } = point;

该功能在 Java 中也是可能的,但需要发明全新的语法,这可能会导致向前兼容性问题。

Java 的哲学之一是向前源代码兼容性:用于在较旧的 JDK 上编译的代码应尽可能继续在未来的 JDK 上编译。很少有例外。

更改

switch
instanceof
同时仍保留向前兼容性比添加全新关键字要容易得多。

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