java - 在 Kotlin 中使用 Room 的 @ForeignKey 作为 @Entity

我遇到了一个房间 tutorial在类定义中使用 @PrimaryKey 注释:

@Entity(foreignKeys = @ForeignKey(entity = User.class,
                              parentColumns = "id",
                              childColumns = "userId",
                              onDelete = CASCADE))
public class Repo {
    ...
}

现在,我有以下要使用主键的数据类:

@Parcel(Parcel.Serialization.BEAN) 
data class Foo @ParcelConstructor constructor(var stringOne: String,
                                              var stringTwo: String,
                                              var stringThree: String): BaseFoo() {

    ...
}

所以,我刚刚添加了 @Entity(tableName = "Foo", foreignKeys = @ForeignKey(entity = Bar::class, parentColumns = "someCol", childColumns = "someOtherCol", onDelete = CASCADE)) 代码 fragment 也在顶部,但我无法编译:

An annotation can't be used as the annotations argument.

我想知道:(我认为是)为什么相同的概念在 Java 中起作用,但在 Kotlin 中却不起作用?另外,有没有办法解决这个问题?

欢迎所有输入。

最佳答案

这是提供您正在寻找的注解的方式,带有用于参数的显式数组,并且没有 @ 用于创建嵌套注解:

@Entity(tableName = "Foo", 
    foreignKeys = arrayOf(
            ForeignKey(entity = Bar::class, 
                    parentColumns = arrayOf("someCol"), 
                    childColumns = arrayOf("someOtherCol"), 
                    onDelete = CASCADE)))

自从 Kotlin 1.2 ,你也可以使用数组字面量:

@Entity(tableName = "Foo",
    foreignKeys = [
        ForeignKey(entity = Bar::class,
                parentColumns = ["someCol"],
                childColumns = ["someOtherCol"],
                onDelete = CASCADE)])

关于java - 在 Kotlin 中使用 Room 的 @ForeignKey 作为 @Entity 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49414476/

相关文章:

java - 安卓3.3.0更新,错误: Cause: invalid type code: 68

kotlin - 我可以省略在 Kotlin 中不使用的接口(interface)方法吗?

android - Kotlin Android 打印到控制台

java - getActionView 已弃用?

kotlin - 如何抑制未经检查的强制转换警告?

java - 为什么可以在 Kotlin 的类之外编写函数?

android - Kotlin - 如何在 "lateinit"和 "nullable varia

hibernate - 如何使用 JpaRepository 进行批量(多行)插入?

properties - 将静态变量从 Java 转换为 Kotlin

kotlin - 如果事件是用 Kotlin 编写的,则按钮 onClick 属性为无