首页 文章

使用具有不可变Kotlin实体的Room

提问于
浏览
1

我试图将不可变的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 Room实体:

@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.

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

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

1 回答

  • 0

    而不是在kotlin中使用普通的java class 使用 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 = "")
    

相关问题