I haven't yet had the luxury to experiment with the latest version of Java, but this is one of the reasons why I wish Java introduced named parameters the say way kotlin and scala do.
Eg:
data class Make(makeId: String, name: String)
data class Model(modelId: String, name: String)
data class Car(make: Make, model: Model, year: String, ...)
Now you can go ahead and order the params whichever way you wish so long as you're explicitly naming them:
val v1 = Car(make = myMake1, model = myModel1, year = "2023", ...)
val v1 = Car(model = myModel1, make = myMake1, year = "2023", ...)
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();
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.
Eg:
Now you can go ahead and order the params whichever way you wish so long as you're explicitly naming them: