B W
B W

Reputation: 702

Does Room allow a non-primitive data type as the primary key?

Using Room, I want to write a Kotlin @Entity with a non-primitive data type as its @PrimaryKey. For example:

@Entity
data class MyEntity(
    @PrimaryKey val myType: MyType,
    val text: String
)

I am providing a TypeConverter between my non-primitive type to/from a String.

class Converters {
    @TypeConverter fun fromString(value: String): MyType = MyTypeUtil.parse(value)
    @TypeConverter fun toString(myType: MyType) = myType.toString()
}

I'm also properly registering my TypeConverters on my database:

@Database(
    entities = [
        MyEntity::class
    ],
    version = 1
)
@TypeConverters(
    Converters::class
)
abstract class MyDatabase : RoomDatabase() {

    abstract fun myDao(): MyDao
}

Compilation is failing with:

...MyDao_Impl.java: uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.

Can you help me find the problem? Does Room allow what I'm trying to do?

Upvotes: 2

Views: 732

Answers (1)

Michał Pawlik
Michał Pawlik

Reputation: 776

Yes - Room allow non-primitive data types as the primary key.

You have bug in your TypeConverters - you must provide conversions from String to MyType and from MyType to String, so method fromString must return MyType (right now it is returning String). Change that and it should work :)
If you would still be having weird compile errors, try to Clean Project after making the changes.

Upvotes: 2

Related Questions