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?
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".
Static Variables & Methods As with regular Java classes, we can also include static variables and methods in our records.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With