@Entity
data class ProductEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Int,
@ColumnInfo(name = "productId")
val productId: String,
@ColumnInfo(name = "types")
val types: List<String>,
)
fun RetrofitProduct.toEntity(): ProductEntity {
return ProductEntity(
productId = this.id,
types = this.types,
)
}
但在构建时间,编译器抱怨我需要添加id
我希望该ID由房间生成,以获取我的页面的项目数量。基本上,如果我拉上lastItem,我知道与ID一起使用:25。所以我需要要求26及更多。
在使用房间和自动生成的ID时,这实际上是一个很常见的陷阱。 问题在于,即使您将ID标记为自动源= True,Kotlin仍然需要在构造函数中提供所有参数,因为Productentity是数据类。这是解决此问题的几种方法:
最快的修复 - 提供默认值为0:
kotlinCopy@Entity data class ProductEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: Int = 0, // Add this default value @ColumnInfo(name = "productId") val productId: String, @ColumnInfo(name = "types") val types: List<String>, )
或如果您希望在映射器中更加明确:
kotlinCopyfun RetrofitProduct.toEntity(): ProductEntity {
return ProductEntity(
id = 0, // Room will ignore this and auto-generate
productId = this.id,
types = this.types,
)
}