在Kotlin中使用Room的@ForeignKey作为@Entity参数

Chi*_*sko 27 java android kotlin java-annotations android-room

我遇到了一个使用类定义注释的Room 教程@PrimaryKey:

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

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

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

    ...
}
Run Code Online (Sandbox Code Playgroud)

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

注释不能用作注释参数.

我想知道:为什么(我认为是)使用Java而不是在Kotlin中使用相同的概念?还有,有办法解决这个问题吗?

欢迎所有输入.

zsm*_*b13 68

这是提供您正在寻找的注释的方法,使用显式的参数数组,而不是@嵌套注释的创建:

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

Kotlin 1.2开始,你也可以使用数组文字:

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