r/java • • Jan 22 '26

Carrier Classes; Beyond Records - Inside Java Newscast

https://youtu.be/cpGceyn7DBE
85 Upvotes

81 comments sorted by

View all comments

Show parent comment

15

u/Puzzleheaded-Eye6596 Jan 22 '26

records can get horrible to instantiate. named arguments would be so helpful

1

u/OwnBreakfast1114 Jan 23 '26

Honestly, we have a ton of like 15 parameter records and all arg constructors. I wouldn't say it's that bad, at least we get compiler errors everywhere when we add a new field to the record (most common update to a record by far).

Mutating state with a with doesn't get called out when you add a new field, which is convenient, but can hide bugs if you imagine that any with/copy constructor is actually an operation that someone should verify isn't broken with a new field addition.

1

u/KrakenOfLakeZurich Jan 23 '26

Not entirely sure, but I think this can be alleviated a bit, once we get withers. Then one can then simply define a "template" instance and instantiate modified copies of that. Something like this (forgive the syntax, I have no Idea, how withers are going to eventually look like):

record Point3D(int x, int y, int z) {
    public final static Point3D DEFAULT = new Point3D(0, 0, 0);
}

and used like this:

var thePoint = Point3D.DEFAULT with { x = 10, y = 45 };

4

u/Puzzleheaded-Eye6596 Jan 23 '26

Just want to note I recently learned Project Lombok supports the \@With annotation which allows for just this

```
record MyRecord (
int id,
int recordCount,
\\@With
String name ){}
...
myRecord.withName("jim");
```