Java 14 records canonical constructor
Christian Beikov
christian.beikov at gmail.com
Thu Jun 4 18:43:39 UTC 2020
Am 04.06.2020 um 20:24 schrieb Johannes Kuhn:
> They need to be mutable to do defensive copies, thereby enforcing deep
> immutability. Consider this:
>
> public record UserRecord(String userName, List<String> mailAddresses) {
> public UserRecord {
> mailAddresses = List.copyOf(mailAddresses);
> }
> }
>
> Records would be a lot less useful if this is not possible.
This could be done through a static factory method as well.
public record UserRecord(String userName, List<String> mailAddresses) {
public static UserRecord create(String userName, List<String>
mailAddresses) {
return new UserRecord(userName, List.copyOf(mailAddresses));
}
}
I understand the need for that and that it is nice to have a compact
source representation for doing this(the static factory method requires
boilerplate again), but it feels wrong to me to mutate the argument in
any way in the canonical constructor. It would be nice to have something
like a compact named constructor, syntax sugar for a static method,
where you can do such normalizations but in the end delegates to the
canonical constructor. Something like the following:
public record UserRecord(String userName, List<String> mailAddresses) {
public UserRecord create {
mailAddresses = List.copyOf(mailAddresses);
}
}
This would ensure the canonical constructor always assigns the arguments
to the respective record components so that a de-construction followed
by a construction always succeeds.
More information about the amber-dev
mailing list