Do I need immutable collections in @AutoValue classes?

310 Views Asked by At

Is a class generated with @AutoValue immutable? Can I use it instead of creating the class myself and making sure it can be annotated @Immutable?

1

There are 1 best solutions below

7
John Caron On

AutoValue is advertised as "Generated immutable value classes for Java 7+". But if you use mutable fields, the AutoValue class is not @Immutable, that is, does not follow the contract defined in the annotation javadoc. This is clearly pointed out in the Autovalue docs.

Further, if you declare a property in an AutoValue class that is a Collection, like

    public abstract Map<String, ImmutableThing> thingMap();

The resulting field is not necessarily immutable, it depends on what implementation of Map you pass into the constructor. For immutability, you want to use something like ImmutableMap instead, which forces you to pass in an ImmutableMap in the constructor:

    public abstract ImmutableMap<String, ImmutableThing> thingMap();

It does seems to me that the generated AutoValue code could have automatically made collection properties like this immutable.

I imagine the @AutoValue designers had good reasons for their design, but the lack of immutability is surprising.