Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 769
sdgfsdh Avatar asked Feb 04 '21 15:02

sdgfsdh


People also ask

How do records work in Java?

A record class declares a sequence of fields, and then the appropriate accessors, constructors, equals , hashCode , and toString methods are created automatically. The fields are final because the class is intended to serve as a simple "data carrier".

Can Java records have methods?

Static Variables & Methods As with regular Java classes, we can also include static variables and methods in our records.

How do you write a record in Java?

To create a record, call its constructor and pass all the field information in it. We can then get the record information using JVM generated getter methods and call any of generated methods.

Are Java records still a preview feature?

Records were introduced as a preview feature in Java 14, in an effort to reduce boilerplate code when writing POJO based data carrier classes. This is something that's been there in Kotlin for long in the form of data classes. Now, with Java 15, Records get their second preview.


1 Answers

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.

like image 177
Adrian Johnson Avatar answered Oct 21 '22 06:10

Adrian Johnson