Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

java - Do I need immutable collections in @AutoValue classes?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...