在 Kotlin 中使用 @Parcelize 注释时如何忽略字段

How to ignore fields when using @Parcelize annotation in Kotlin

我想在 Kotlin 中使用 @Parcelize 注解时忽略一个字段,这样该字段就不会被打包,因为这个字段没有实现 Parcelable 接口。

从这里开始,我们收到一个错误,因为 PagedList 不可打包:

@Parcelize
data class LeaderboardState(
    val progressShown: Boolean = true,
    val pagedList: PagedList<QUser>? = null
) : Parcelable

给出:

Type is not directly supported by 'Parcelize'. Annotate the parameter type with '@RawValue' if you want it to be serialized using 'writeValue()'

标记为 @Transient 给出与上面相同的错误:

@Parcelize
data class LeaderboardState(
    val progressShown: Boolean = true,

    //Same error
    @Transient
    val pagedList: PagedList<QUser>? = null
) : Parcelable

我发现了一个名为 @IgnoredOnParcel 的未记录的注释,它给出了同样的错误,注释上有一个 lint 错误:

@Parcelize
data class LeaderboardState(
    val progressShown: Boolean = true,

    //Same error plus lint error on annotation
    @IgnoredOnParcel
    val pagedList: PagedList<QUser>? = null
) : Parcelable

这种情况下的 lint 错误是: @IgnoredOnParcel' is inapplicable to properties declared in the primary constructor

真的没有办法用@Parcelize 做到这一点吗?

使用常规 class 并将 属性 移出主构造函数:

@Parcelize
class LeaderboardState(
    val progressShown: Boolean = true,
    pagedList: PagedList<QUser>? = null
) : Parcelable {

    @IgnoredOnParcel
    val pagedList: PagedList<QUser>? = pagedList
}

这显然是唯一的解决办法。确保根据需要覆盖 equals、hashCode、toString、copy 等,因为它们不会为常规 class.

定义

编辑:这是另一个解决方案,这样您就不会丢失数据的特征 class,也不会丢失自动分割。我在这里使用的是一般示例。

data class Person(
    val info: PersonInfo
    val items: PagedList<Item>? = null)

@Parcelize
data class PersonInfo(
    val firstName: String,
    val lastName: String,
    val age: Int
) : Parcelable

您只保存 Person.info 并从中重新创建它。