Leo Aso
Leo Aso

Reputation: 12463

Parcelize complains "Parcelable should be a class" on objects and enums

When I try to annotate an enum class or object with @Parcelize, it results in the error 'Parcelable' should be a class, both as an editor hint and as a compile failure. I can @Parcelize classes just fine, but I can't do things like

@Parcelize object MySingletion : Parcelable
@Parcelize enum class Direction : Parcelable { N, E, W, S }

This happens even though the Kotlin website explicitly states that objects and enums are supported. Is there a way to fix this so that I can @Parcelize these types of classes? And ideally, is there a solution that doesn't involve manually coding the parceler logic?

Upvotes: 5

Views: 8935

Answers (2)

veyndan
veyndan

Reputation: 382

Since Kotlin 1.2.60, the CHANGELOG states that Parcelize works with object and enum types.

Upvotes: 8

tynn
tynn

Reputation: 39843

The documented support means, that objects and enums are properly handled when used as properties on the class being parcelized. More importantly both types are implicitly excluded from the usage, as the fields have to be properties defined within the primary constructor:

@Parcelize requires all serialized properties to be declared in the primary constructor. Android Extensions will issue a warning on each property with a backing field declared in the class body. Also, @Parcelize can't be applied if some of the primary constructor parameters are not properties.

If you need to use your objects or enums as a property only, there's no issue with it. If you want to use it as a Parcelable, you can't get around implementing the interface by yourself, since both types are a kind of a singleton implementation and @Parcelize only supports types with accessible constructors with properties.

Upvotes: 5

Related Questions