我正在使用 Kotlin 和 Realm 编写一个数据类
data class AuthToken(val register: Boolean,
val token: String,
val tokenSecret: String,
val user: AuthUser)
我必须将数据保存到 db,所以我使用 Realm 来保存它。但是我们知道,如果我想将类保存到 Realm,AuthToken
类必须扩展 RealmObject
。
这就是问题所在,Kotlin 说数据类不能扩展类。 所以我放弃了数据类,只使用一个普通的 Kotlin 类作为模型,那么另一个问题来了:
Kotlin 类没有 getter 或 setter。正如我们所知,Realm 类必须将所有属性设置为私有(private)并编写 getter 和 setter。
现在我想知道如何解决这个问题。
最佳答案
Realm 目前不支持 Data 类。您可以在此处查看如何在 Kotlin 中编写 Realm 兼容模型类的示例:https://github.com/realm/realm-java/tree/master/examples/kotlinExample/src/main/kotlin/io/realm/examples/kotlin/model
public open class Person(
@PrimaryKey public open var name: String = "",
public open var age: Int = 0,
public open var dog: Dog? = null,
public open var cats: RealmList<Cat> = RealmList(),
@Ignore public open var tempReference: Int = 0,
public open var id: Long = 0
) : RealmObject() {
https://stackoverflow.com/questions/34368374/