找不到字段的设置器-将Kotlin与Room数据库一起使用 [英] Cannot find setter for field - using Kotlin with Room database
问题描述
我正在与Room持久性库集成.我在Kotlin中有一个数据类,例如:
I'm integrating with the Room persistence library. I have a data class in Kotlin like:
@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库.当我尝试构建时,它失败并显示错误:
The @Entity
and @PrimaryKey
annotations are for the Room library. When I try to build, it is failing with error:
Error:Cannot find setter for field.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
我还尝试提供默认的构造函数:
I also tried providing a default constructor:
@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类,则它可以工作.感谢您的帮助!
But this doesn't work as well. A thing to note is that it works if I convert this Kotlin class into a Java class with getters and setters. Any help is appreciated!
推荐答案
由于您的字段已标记为val
,因此它们实际上是最终字段,并且没有设置器字段.
Since your fields are marked with val
, they are effectively final and don't have setter fields.
尝试用var
切换val
.
您可能还需要初始化字段.
Try switching out the val
with var
.
You might also need to initialize the fields.
@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与Room数据库一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!