6

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

爪哇:

public record Vehicle(String brand, String licensePlate) {}

毫升:

type Vehicle = 
  {
    Brand : string
    LicensePlate : string
  }

在 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"
  }

这在 Java 14 中可能吗?

4

1 回答 1

5

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

public static Vehicle withLicensePlate(Vehicle a, String newLicensePlate) {
    return new Vehicle(a.brand, newLicensePlate);
}

像这样使用:

Vehicle a = new Vehicle("Subaru", "ABC-DEFG");
Vehicle b = Vehicle.withLicensePlate(a, "LMN-OPQR");

这将为您提供与您尝试使用“with”标签的结果类似的结果。您可以将其用作更新记录的一种方式。

于 2021-02-04T16:52:21.540 回答