sdgfsdh
sdgfsdh

Reputation: 37105

Do Java records support "with" syntax?

Java 14 brings records, which are a great addition seen in many functional languages:

Java:

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

ML:

type Vehicle = 
  {
    Brand : string
    LicensePlate : string
  }

In ML languages, it is possible to "update" a record by creating a copy with a few values changed:

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

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

// Same as: 
let v = 
  {
    Brand = u.Brand
    LicensePlate = "LMN-OPQR"
  }

Is this possible in Java 14?

Upvotes: 9

Views: 1639

Answers (1)

Adrian Johnson
Adrian Johnson

Reputation: 78

Unfortunately, Java does not include this functionality. Though, you could create a utility method that takes in a different license plate value:

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

Used like so:

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

This would give you a similar result to what you were attempting using the "with" tag. And you can use this as a way to update the record.

Upvotes: 6

Related Questions