android - 如何将 Room 库的 @Ignore 注释与 Kotlin 紧凑构造函数语法一起使用?

标签 android kotlin android-room

我正在尝试使用 android Room 库和 Kotlin 的紧凑语法来指定具有默认参数值的构造函数。像这样:

@Entity
class MyEntity(var myString:String = "non-trivial string") {

    @PrimaryKey(autoGenerate = true)
    var myIndex:Int = 0
}

但是我收到这条警告信息:

There are multiple good constructors and Room will pick the no-arg constructor. You can use the @Ignore annotation to eliminate unwanted constructors.

语法在哪里允许使用这种紧凑的 Kotlin 构造函数编写 Room 的 @Ignore 注释?

我知道我可以做这样的事情来消除警告信息,但它更冗长。它还使构造函数 arg 默认值看起来多余/无用:

@Entity
class MyEntity() {

    @Ignore
    constructor(myString:String = "non-trivial string") : this() {
        this.myString = myString
    }

    @PrimaryKey(autoGenerate = true)
    var myIndex:Int = 0

    var myString:String? = null
}

如何在声明 Room 实体的同时仍然利用 Kotlin 的简洁性?

谢谢你。

最佳答案

如果要给主构造函数添加注解,则必须添加constructor关键字:

class MyEntity @Ignore constructor(var myString:String = "non-trivial string")

documentation状态:

If the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted.

关于android - 如何将 Room 库的 @Ignore 注释与 Kotlin 紧凑构造函数语法一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673808/

相关文章:

android - Jetpack 组成 : Pending composition has not been applied when rememberSaveable is used

Android Room 使用 Migration 更改列的类型

android - Room 生成的类的发布构建失败 : javax. 注释不存在

android - Room Dao 返回插入 ID,但数据库中缺少数据

java - Fragment 中的 Android 登录按钮

android - KtLint 任务 ':app:ktlintAndroidTestDebugSourceSetCheck' 执行失败

java - 异常 : Caused by: java. lang.NullPointerException: Assets

android - React-Native 通过 HTTP 发送 multipart/form-data

android - Kotlin DataBinding : IncompleteAnnotationException: android. databinding.BindingBuildInfo 缺少元素

android - Lambda无法在Kotlin中进行多线程操作