immutables icon indicating copy to clipboard operation
immutables copied to clipboard

List-style builders for array members

Open devinrsmith opened this issue 4 years ago • 1 comments

It would be great if the builder code for arrays was similar to the builder code for lists. Specifically, I'm hoping to be able to build up the object one element at a time, as opposed to passing it all in at once.

@Immutable
public abstract class MyArray<T> {
    public abstract T[] values();
}
@Immutable
public abstract class MyList<T> {
    public abstract List<T> values();
}

I think it would also be really beneficially to have specialized builder code for each primitive array:

@Immutable
public abstract class MyIntArray {
    public abstract int[] values();
}

devinrsmith avatar Jul 01 '21 13:07 devinrsmith

Sorry for delay, just to share some background: it was an early decision to handle arrays they way they are. Any time you want to use array with an immutable object - you're almost every time better served with the immutable list or set. Those are guaranteed to be immutable. Arrays can be changed/mutated, so we need to make defensive copy every time an array accessed, that is not a normal usage for most cases. As such we don't do all the niceties for arrays as we do for lists etc. The easiest thing you can do is just store list and convert it to array any time you want, at least you will be in control when copy is actually created. I know it seems strange that you asked about simple thing "X" and I'm explaining some else "Y", but that is why we don't do "X" from the very beginning and there is no much value is doing so. If order to have all the niceties and have protected copy/immutable arrays, I would suggest go "the heavy route" of Encodings to fully customize all the add* and other niceties whey way you want.

elucash avatar Sep 13 '21 23:09 elucash