首页 文章

kotlin-room无法弄清楚如何保存这个字段

提问于
浏览
1

我在Kotlin开始了我的第一个Android项目 . 官方文件建议我使用我做的房间 .

添加Room后我无法编译我的项目 .

无法弄清楚如何将此字段保存到数据库中 . 您可以考虑为其添加类型转换器 .

Extra info about the error

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和房间的版本是:

  • 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"

我还添加在文件的顶部:

apply plugin:'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和getters(这似乎不允许在Kotlin中)

  • 将var设置为val

有人经历过同样的问题并修复了吗?

感谢您的时间!

ps . :我不经常在Stackoverflow上发布关于我提出问题的方式的反馈意见会被接受 .

1 回答

  • 0

    为什么你有 constructor() ?您已经使用了定义构造函数

    data class TodoData(
        @PrimaryKey(autoGenerate = true)
        var od: Long? = null,
        var firstName: String = "",
        var lastName: String = ""
     )
    

    删除 constructor ,一切都应该没问题 .

相关问题