android - 找不到字段的 setter - 将 Kotlin 与 Room 数据库结合使用

标签 android kotlin android-room

我正在与 Room 持久性库集成。我在 Kotlin 中有一个数据类,例如:

@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
)

@Entity@PrimaryKey 注释用于 Room 库。当我尝试构建时,它失败并出现错误:

Error:Cannot find setter for field.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

我也尝试过提供默认构造函数:

@Entity(tableName = "story")
data class Story (
        @PrimaryKey val id: Long,
        val by: String,
        val descendants: Int,
        val score: Int,
        val time: Long,
        val title: String,
        val type: String,
        val url: String
) {
    constructor() : this(0, "", 0, 0, 0, "", "", "")
}

但这也不起作用。需要注意的是,如果我将这个 Kotlin 类转换为带有 getter 和 setter 的 Java 类,它就可以工作。任何帮助表示赞赏!

最佳答案

由于您的字段标有 val,因此它们实际上是最终的并且没有 setter 字段。

尝试用 var 切换 val。 您可能还需要初始化字段。

@Entity(tableName = "story")
data class Story (
        @PrimaryKey var id: Long? = null,
        var by: String = "",
        var descendants: Int = 0,
        var score: Int = 0,
        var time: Long = 0L,
        var title: String = "",
        var type: String = "",
        var url: String = ""
)

编辑

上述解决方案是对 Kotlin 中此错误的一般修复,当我将 Kotlin 与其他 Java 库(如 Hibernate)一起使用时,我也看到了这一点。如果您想保持 Room 的不变性,请参阅其他一些答案,这些答案可能更适合您的情况。

在某些情况下,Java 库的不变性根本无法正常工作,并且在给开发人员带来可悲的噪音时,不幸的是,您必须将 val 切换为 var

关于android - 找不到字段的 setter - 将 Kotlin 与 Room 数据库结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44213446/

相关文章:

java - Kotlin 类似于 Java 中的选择器

kotlin - Ktor 无法正确提供静态图像

android - 刷新 fragment 回到上一个 fragment

android - 如何从 Android RoomDB 中的字符串列表中查询特定字符串

node.js - socket.io 在连接时加入多个房间

android - 如何让我的所有 Activity 都听到设备的震动?

android - 锚定到应用栏的 FAB 不会在向上滚动时隐藏

java - 如何在 ListView 项目的对话框上显示自定义消息

javascript - 在不重新加载页面的情况下更改 Android Webview 哈希

javafx - 将可观察属性绑定(bind)到集合函数?