Varargs records

Brian Goetz brian.goetz at
Fri Aug 16 01:14:07 UTC 2019

That's not exactly true; it's not broken, but it's possibly not what 
people expect.  The implicit implementations of ctor/accessor/and equals 
work together; the ctor copies the reference, the accessor dispenses the 
reference, and equals compares by reference equality.  So you get the 
invariants you expect, but you end up exposing the mutability of the 
array (until we have frozen arrays, which I desperately want, for this 
very reason.)

If you wanted to make the record more bulletproof, you'd have to:

     record R(STUFF, String... strings) {
         R { strings = strings.clone(); }

         public String[] strings() { return strings.clone(); }

         public boolean equals(Object o) {
             return o instanceof R r && ... STUFF ... && 
Arrays.equals(strings, r.strings);

which is kind of messy but not ... awful.

But either way, people can use arrays in records -- this just makes it 
more likely that they will.

On 8/15/2019 8:57 PM, Tagir Valeev wrote:
> Allowing this would encourage people to use arrays in records. 
> Unfortunately, according to current spec they will have broken 
> equals/hashCode. Especially in vararg mode: you will always have a new 
> array, so no record will be equal to another one unless explicit array 
> is used instead of vararg. Is this what we want?
> With best regards,
> Tagir Valeev.
> пт, 16 авг. 2019 г., 1:35 Brian Goetz <brian.goetz at 
> <mailto:brian.goetz at>>:
>     As I was writing some tests for records, it occurs to me that we
>     never
>     explicitly discussed whether we should support _varargs_ records,
>     such as:
>          record StringBunch(String... strings) { }
>     The translation would be straightforward:
>       - The type of the strings field is String[]
>       - The return type of the strings accessor is String[]
>       - The canonical constructor is of descriptor (String...) rather
>     than
>     (String[]), allowing varargs invocation of the constructor.
>       - There would be the usual restriction that there can be only one
>     varargs argument, and it must be last.
>     So this seems feasible.  Is this something we want?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the amber-spec-experts mailing list