49

I came across a Room tutorial that makes use of the @PrimaryKey annotation on the class definition:

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

Now, I have the following data class that want to use a primary key on:

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

    ...
}

So, I just added the @Entity(tableName = "Foo", foreignKeys = @ForeignKey(entity = Bar::class, parentColumns = "someCol", childColumns = "someOtherCol", onDelete = CASCADE)) snippet on the top as well, but I can't compile:

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

I wonder: how come (what I think is) the same concept working in Java but not in Kotlin? Also, is there a way to go around this?

All input is welcome.

1 Answer 1

121

This is the way to provide the annotation you're looking for, with explicit arrays for the arguments, and no @ for the nested annotation's creation:

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

Since Kotlin 1.2, you can also use array literals:

@Entity(tableName = "Foo",
    foreignKeys = [
        ForeignKey(entity = Bar::class,
                parentColumns = ["someCol"],
                childColumns = ["someOtherCol"],
                onDelete = CASCADE)])
2
  • 1
    someCol is part of class for your example Foo and someOtherCol is for xlass BAr ?
    – kiki Kala2
    May 13, 2020 at 9:20
  • Actually, the other way around. The child columns are the ones from the current entity (so Foo in this case), and the parent columns are from the other entity (Bar in this case).
    – zsmb13
    May 13, 2020 at 16:47

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.