我正在与 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/