为什么Room实体无法在Android中使用不可变属性 [英] Why Room entities don't work with immutable properties in Android
问题描述
我一直在探索房间数据库对象映射库和我觉得有些奇怪.
I have been exploring Room database object mapping library and I figured something weird.
实体数据模型不能具有不变的属性,如此答案所建议的.
An entity data model cannot have immutable properties, as this answer suggests.
但是我检查了谷歌关于kotlin的持久示例, Room
也可以使用不可变的属性.请检查
But I checked out google's persistent example with kotlin, Room
works with immutable properties too. Please check this data class from the example.
这种行为可能是什么原因?
What could be the reason for this behavior?
如果我们可以创建不可变值(val
属性),那么这可能是一个好功能,因为这会限制程序员在创建对象后更改唯一标识符(例如id).
This could be a good feature if we could create immutable values (val
properties), as this restrict programmers from changing unique identifiers such as ids after an object has been created.
推荐答案
这很奇怪,因为我可以对所有字段使用val
来创建Entity类,而不会出现问题
It's weird because I can make my Entity class using val
for all of my fields without an issue
@Entity(tableName = "repo")
data class RepoEntity(
@PrimaryKey @ColumnInfo(name = "id") @SerializedName("id") val id: Int,
@ColumnInfo(name = "name") @SerializedName("name") val name: String,
@ColumnInfo(name = "full_name") @SerializedName("full_name") val fullName: String,
@Embedded(prefix = "owner") @SerializedName("owner") val owner: RepoOwnerEntity,
@ColumnInfo(name = "html_url") @SerializedName("html_url") val htmlUrl: String,
@ColumnInfo(name = "description") @SerializedName("description") val description: String?
)
并且数据仍然正确存储在数据库中.
And the data still stored correctly inside the Database.
这篇关于为什么Room实体无法在Android中使用不可变属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!