frankiesardo / auto-parcel

Android Parcelable models made easy
Eclipse Public License 1.0
1.37k stars 83 forks source link

Allow true Immutable type objects #32

Closed nohitme closed 9 years ago

nohitme commented 9 years ago

I love this library (and appreciate your effort)!

When I started using this library, I realize one thing that the objects this library creates might not be truly immutable, which violates the purpose of this library or AutoValue.

This is generated code from one of my classes:

private AutoParcel_SpotifyPaging(android.os.Parcel in) {
    this((ImmutableList<T>) in.readValue(CL), (Integer) in.readValue(CL), (Integer) in.readValue(CL), (Integer) in.readValue(CL), (String) in.readValue(CL), (String) in.readValue(CL));
}

which of course crashes when it tries to type cast an ArrayList to an ImmutableList. (In Android the list is always going to be an ArrayList after reading from Parcel and it will be mutable)

However if I change the type of list to List, then the generated code will just take in a List and return it.

Constructor:

if (items == null) {
    throw new NullPointerException("Null items");
}
this.items = items;

Getter:

@Override
public List<T> items() {
    return items;
}

The returned list now becomes mutable.

So is there a way to override the current behavior?

For example to allow getters return ImmutableList but setters in builder take in a generic List. Or allow us to write a concrete setter in builder that won't be extended?

frankiesardo commented 9 years ago

I'm open to suggestions, but I see no way to support immutable collection types.

The only thing that you can do is to write your own immutable List type that implement Parcelable, and use that for every list collection as needed.

Piasy commented 8 years ago

Could we use unmodifiable collections under the hood? Unmodifiable won't kill much performance, but gain the really immutability.