4 ms·
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 w
by kentosi 2y ago
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", ...)
- Ironlink 2y agoOnce 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.
- Tainnor 2y agoSo 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.
- javanonymous 2y agoI 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()