【发布时间】:2018-04-08 19:59:00
【问题描述】:
我在 Kotlin 中开始了我的第一个 Android 项目。官方文档建议我使用 Room。
添加 Room 后,我无法编译我的项目。
无法弄清楚如何将此字段保存到数据库中。您可以考虑为其添加类型转换器。
warning: There are multiple good constructors and Room will pick the
no-arg constructor. You can use the @Ignore annotation to eliminate
unwanted constructors.
public final class TodoData {
^
error: Cannot find setter for field.
private final java.lang.Long id = null;
^
error: Cannot find setter for field.
private final java.lang.String firstName = null;
^
error: Cannot find setter for field.
private final java.lang.String lastName = null;
^
kotlin 和 room 的版本是:
- ext.kotlin_version = '1.2.31'
- ext.room_version = '1.0.0'
我的 gradle.build 依赖项如下所示:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
// Room
implementation "android.arch.persistence.room:runtime:$room_version"
kapt "android.arch.persistence.room:compiler:$room_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
我还在文件顶部添加了:
应用插件:'kotlin-kapt'
这是我的道:
@Entity
data class TodoData(
@PrimaryKey(autoGenerate = true)
var od: Long? = null,
var firstName: String = "",
var lastName: String = ""
){
constructor(): this(od = null, firstName = "", lastName = "")
}
我尝试了什么:
- 更改 Kotlin 版本
- 添加 setter 和 getter(这在 Kotlin 中似乎不允许)
- 将 var 设置为 val
有人遇到过同样的问题并解决了吗?
感谢您的宝贵时间!
ps.:我不经常在 Stackoverflow 上发帖 欢迎对我提出问题的方式提出反馈。
【问题讨论】:
-
请再次检查。上面的代码可以正常工作
-
只是一个补充——你应该使用 val 或 var 的内部数据类。 DataClasses 应该是不可变的。检查此以获取更多信息:kotlinlang.org/docs/reference/data-classes.html 另外 - 删除这个“构造函数”的东西。它实际上什么也没做
-
@muminers 感谢您的提示
-
@SangeetSuresh 我又试了一次,清理了我的项目并重建了它-> 失败了。这次我用更详细的错误日志编辑了我的问题。
-
@Deff : 将“@Ignore”放在数据类构造函数上