如何在使用@Parcelize时将数据class中构造函数以外的成员变量打包
How to parcelise member variable other than constructor in data class while using @Parcelize
我正在使用 Room 和 Kotlin 数据 class。比如,
@Entity(tableName = "Person")
@Parcelize
class Test(@ColumnInfo(name = "name") var name:String) : Parcelable{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "ID")
var id: Long? = null
}
我可以使用构造函数创建实例并插入数据。我也收到警告 "property would not be serialized into a 'parcel'"
。当我试图通过包发送对象时,id 丢失了,正如警告所说,这是预期的。如何在包裹中添加该成员 ID
?我没有在构造函数中保留 ID,因为我希望它们自动生成。
您可以通过 documentation:
找到此信息
@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 your class requires more advanced serialization logic, you can write it inside a companion class:
@Parcelize
data class User(val firstName: String, val lastName: String, val age: Int) : Parcelable {
private companion object : Parceler<User> {
override fun User.write(parcel: Parcel, flags: Int) {
// Custom write implementation
}
override fun create(parcel: Parcel): User {
// Custom read implementation
}
}
}
我正在使用 Room 和 Kotlin 数据 class。比如,
@Entity(tableName = "Person")
@Parcelize
class Test(@ColumnInfo(name = "name") var name:String) : Parcelable{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "ID")
var id: Long? = null
}
我可以使用构造函数创建实例并插入数据。我也收到警告 "property would not be serialized into a 'parcel'"
。当我试图通过包发送对象时,id 丢失了,正如警告所说,这是预期的。如何在包裹中添加该成员 ID
?我没有在构造函数中保留 ID,因为我希望它们自动生成。
您可以通过 documentation:
找到此信息
@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 your class requires more advanced serialization logic, you can write it inside a companion class:
@Parcelize
data class User(val firstName: String, val lastName: String, val age: Int) : Parcelable {
private companion object : Parceler<User> {
override fun User.write(parcel: Parcel, flags: Int) {
// Custom write implementation
}
override fun create(parcel: Parcel): User {
// Custom read implementation
}
}
}