Why Room entities don't work with immutable properties in Android

前端 未结 2 1585
终归单人心
终归单人心 2021-01-01 22:34

I have been exploring Room database object mapping library and I figured something weird.

An entity data model cannot have immutable properties, as this answer sugge

相关标签:
2条回答
  • 2021-01-01 23:03

    It's weird because I can make my Entity class using val for all of my fields without an issue

    @Entity(tableName = "repo")
    data class RepoEntity(
            @PrimaryKey @ColumnInfo(name = "id") @SerializedName("id") val id: Int,
            @ColumnInfo(name = "name") @SerializedName("name") val name: String,
            @ColumnInfo(name = "full_name") @SerializedName("full_name") val fullName: String,
            @Embedded(prefix = "owner") @SerializedName("owner") val owner: RepoOwnerEntity,
            @ColumnInfo(name = "html_url") @SerializedName("html_url") val htmlUrl: String,
            @ColumnInfo(name = "description") @SerializedName("description") val description: String?
    )
    

    And the data still stored correctly inside the Database.

    0 讨论(0)
  • 2021-01-01 23:07

    I believe that the issue stems from certain fields which can not be constructor parameters. From the Javadoc of the @Relation annotation:

    Note that the @Relation annotated field cannot be a constructor parameter, it must be public or have a public setter.

    As a workaround, I had a private constructor parameter _myRelationProperty and a public field:

    val myRelationProperty: List<MyThings> get() = _myRelationProperty
    
    0 讨论(0)
提交回复
热议问题