Java 记录是否支持“with”语法?

sdg*_*sdh 5 java java-14 java-record

Java 14 带来了记录,这是许多函数式语言中的一个很好的补充:

爪哇:

public record Vehicle(String brand, String licensePlate) {}
Run Code Online (Sandbox Code Playgroud)

毫升:

type Vehicle = 
  {
    Brand : string
    LicensePlate : string
  }
Run Code Online (Sandbox Code Playgroud)

在 ML 语言中,可以通过创建一个更改了一些值的副本来“更新”记录:

let u = 
  {
    Brand = "Subaru"
    LicensePlate = "ABC-DEFG"
  }

let v =
  {
    u with 
      LicensePlate = "LMN-OPQR"
  }

// Same as: 
let v = 
  {
    Brand = u.Brand
    LicensePlate = "LMN-OPQR"
  }
Run Code Online (Sandbox Code Playgroud)

这在 Java 14 中可能吗?

小智 6

不幸的是,Java 不包含此功能。不过,您可以创建一个接受不同车牌值的实用方法:

public static Vehicle withLicensePlate(Vehicle a, String newLicensePlate) {
    return new Vehicle(a.brand, newLicensePlate);
}
Run Code Online (Sandbox Code Playgroud)

像这样使用:

Vehicle a = new Vehicle("Subaru", "ABC-DEFG");
Vehicle b = Vehicle.withLicensePlate(a, "LMN-OPQR");
Run Code Online (Sandbox Code Playgroud)

这将为您提供与尝试使用“with”标签类似的结果。您可以使用它来更新记录。

  • 正确的声明是“public Vehicle(Vehicle a, String newLicensePlate) { this(a.brand, newLicensePlate); }` 但无论如何这是一个不好的模式。构造函数的参数类型并不指示参数是新品牌还是新车牌,并且当两个元素具有相同类型时,两个元素的支持构造函数根本不起作用。更简洁的方法是在记录中添加一个*方法*,例如`public Vehicle withLicensePlate(String newLicensePlate) { return new Vehicle(brand, newLicensePlate); }` 可以像 `Vehicle b = a.withLicensePlate("LMN-OPQR");` 一样使用 (6认同)
  • @Naman我知道OP要求一种自动性,不幸的是它还不存在(还?)。我刚刚回复了建议构造函数的答案,而方法会更好。 (2认同)