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

问题描述 投票:1回答:1

我想在使用的时候忽略一个字段。@Parcelize 注解,所以这个字段不会被包裹,因为这个字段没有实现Kotlin中的 Parcelable 接口。

开始,我们得到一个错误,因为 PagedList 是不能包裹的。

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

Gives:

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

Marking as @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来做这个吗?

android kotlin parcelable
1个回答
2
投票

使用普通类,并将属性从主构造函数中移出。

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

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

这显然是唯一的解决办法 确保在你需要的时候重写equals、hashCode、toString、copy等,因为它们不会被定义为一个常规类。

EDIT:这里有另一个解决方案,这样你就不会失去数据类的特性,也不会失去自动解析的功能。我这里用的是一个普通的例子。

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 并从中重新创造。

© www.soinside.com 2019 - 2024. All rights reserved.