Once withers land, I think you could approximate this by letting your record class have a zero argument constructor which sets every field to some blank value, and then fill the fields using `with`.
var x = new Car() with { make = "Volvo"; year = "2023"; };
If you want the Car constructor to enforce constraints, you could use this pattern in a separate Builder record: record Car(String make, String year) {
Car {
Objects.requireNonNull(make);
Objects.requireNonNull(year);
}
record Builder(String make, String year) {
Builder() {
this(null, null);
}
Car build() {
return new Car(make, year);
}
}
}
var x = new Car.Builder() with { make = "Volvo"; year = "2023"; }.build();
Obviously syntax TBD.So much syntax to enable something that other languages have had for 10+ years. That's why I can't take the "Java is as good as Kotlin now" arguments seriously.
Re:Show HN: I Wrote a Book on Java
by javanonymous on Tuesday September 24, 2024 @07:06AM
(#41635269)
I think named parameters would be a great addition
For now, I use Lombok's @Builder annotation. It makes it much easier to create and copy a record, where non-assigned attributes are set to default.
Example:
var bmw = Car.builder().make("BMW").build()
It also has a practical toBuilder() syntax that creates a copy of the original record, with some attributes changed var other = bmw.toBuilder().year(2024).build()
Eg:
Now you can go ahead and order the params whichever way you wish so long as you're explicitly naming them: