将 Room 与不可变的 Kotlin 实体一起使用



我试图将不可变的Java类转换为Kotlin,但失败了。

前提 条件:

global build.gradle:

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"

Module build.gradle

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
...
kapt "android.arch.persistence.room:compiler:$roomVersion"
...
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"

Java 会议室实体:

@Immutable
@Entity
public class User {
    @PrimaryKey
    @SerializedName("user_id")
    @Expose
    private final int userId;
    @SerializedName("display_name")
    @Expose
    private final String userName;
    @SerializedName("amount")
    @Expose
    private final String amount;
    @SerializedName("has_access")
    @Expose
    private final String hasAccess;
    public User(final int userId, final String userName,
                final String amount, final String hasAccess) {
        this.userId = userId;
        this.userName = userName;
        this.amount = amount;
        this.hasAccess = hasAccess;
    }
    public int getUserId() {
        return userId;
    }
    public String getUserName() {
        return userName;
    }
    public String getAmount() {
        return amount;
    }
    public String getHasAccess() {
        return hasAccess;
    }
} 

转换为 Kotlin 的同一实体:

class User(@field:PrimaryKey
                @field:SerializedName("user_id")
                @field:Expose
                val userId: Int,
                @field:SerializedName("display_name")
                @field:Expose
                val userName: String,
                @field:SerializedName("amount")
                @field:Expose
                val amount: String,
                @field:SerializedName("has_access")
                @field:Expose
                val hasAccess: String)

Java 实体工作没有任何问题,但转换为 Kotlin 会导致下一个 buid 错误:

e: error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
e: error: Cannot find setter for field.

摘要问题:如何正确使用不可变的 Kotlin 实体和房间持久性库?

更新:用户数据库和 dao 位于与用户模型模块分开的位置。似乎 Room 不适用于 Kotlin 为 val 属性添加的构造函数括号中的@NotNull、@NonNull、@Nullable。即使将它们添加到 java 构造函数中也会导致相同的错误。

而不是使用普通的java class在kotlin中使用data class,你会得到所有的getter,equals,hashCode方法的权利。

data class User(@PrimaryKey @ColumnInfo(name = "user_id") val userId: Long,
            @ColumnInfo(name ="display_name") val userName: String = "",
            @ColumnInfo(name ="amount") val amount: String = "",
            @ColumnInfo(name ="has_access") val hasAccess: String = "") 

最新更新