我一直在探索Room个数据库对象映射库,我发现了一些奇怪的事情.

正如this答案所示,实体数据模型不能具有不变的属性.

但我也判断了google's persistent example with kotlinRoom个具有不可变属性的作品.请判断示例中的this数据类.

这种行为的原因可能是什么?

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(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?
)

数据仍然正确地存储在数据库中.

Kotlin相关问答推荐

Regex(Kotlin)仅匹配句子末尾的句号,而忽略中间的句号,如缩写

为什么Kotlin函数参数名会 destruct 方法调用?

映射中列表类型的Kotlin可空接收器?

在Kotlin中,我是否可以访问已知的WHEN子句值?

为什么 Kotlin 中没有 init 块的注释

Rabin-Karp字符串匹配的实现(Rolling hash)

MyType.()在 Kotlin 中是什么意思?

Flow.state In() 未从其来源接收新值

如何为 Kotlin 中的每个循环设置以避免越界异常

Mixin 在 Jackson 中添加 defaultImpl 不起作用

Jetpack compose 可滚动表格

kotlin 扩展属性的惰性初始化器中的这个引用

在构造函数中仅注入某些参数

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

Kotlin解构when/if语句

如何捕获传递给模拟函数的参数并返回它?

如何在Kotlin中使方法param可变?

Mocked suspend函数在Mockito中返回null

Kotlin 的数据类 == C# 的 struct ?

带有注释为@RegisterExtension的字段的 JUnit 5 测试在 Kotlin 中不起作用