android - 找不到字段的 setter - 将 Kotlin 与 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/

相关文章:

android - 如何在 Android 上使用 Kotlin 显示 Toast?

kotlin - 什么时候应该更喜欢 Kotlin 扩展函数?

kotlin - 在 Android Studio 中构建时如何解决错误 "Failed to re

spring - 如何在基于 Spring 的强类型语言中正确执行 PATCH - 示例

java - 在 Kotlin 中定义 log TAG 常量的最佳方法是什么?

constructor - 如何在 Kotlin 中扩展具有多个构造函数的类?

java - 在 Kotlin 中同时扩展和实现

kotlin - Kotlin 中的 crossinline 和 noinline 有什么区别?

kotlin - Kotlin 中线程和协程的区别

android - 在当前主题中找不到样式 'cardView Style'