【发布时间】:2018-09-23 13:27:19
【问题描述】:
我尝试将不可变的 Java 类转换为 Kotlin,但失败了。
前提条件:
全局 build.gradle:
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
模块构建.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 构造函数中也会导致相同的错误。
【问题讨论】:
标签: kotlin android-room