I'm using Kotlin and Realm to write a data class

data class AuthToken(val register: Boolean,
                     val token: String,
                     val tokenSecret: String,
                     val user: AuthUser)

我必须将数据保存到数据库中,所以我使用Realm来保存它.但正如我们所知,如果我想将类保存到Realm,AuthToken类必须扩展RealmObject.

That's the problem, Kotlin says data classes can't extend classes. so I give up data class, just using a normal Kotlin class as a model then another question comes:

Kotlin class has no getter or setter. As we know Realm class have to set all the property private and write getter and setter.

Now i'm wondering how to solve the problem.

推荐答案

Realm目前不支持数据类.您可以在这里看到如何在Kotlin中编写领域兼容模型类的示例: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() {

Kotlin相关问答推荐

Lambda和普通Kotlin函数有什么区别?

Kotlin—从列表中枚举属性计算不同值的数量

文本正在被切断在200%的屏幕比例在Jetpack Compose

为什么在Spring中,对事务性方法调用的非事务方法调用仍然在事务中运行?

如何进行基于lambda/谓词的两个列表的交集?

Kotlin stlib中是否有用于将列表<;对<;A,B&>;转换为对<;列表<;A&>,列表<;B&>;的函数

为什么不';Kotlin是否在数据类构造函数中隐式分配null值可为null的字段?

Gradle:无法创建 ExtensiblePolymorphicDomainObjectContainer

如何在 Jetpack Compose 中启动和停止动画

如何创建扩展函数isNullOrEmpty?

使用空键映射获取

Kotlin 具体类从抽象类和接口扩展而来,接口使用抽象类中实现的方法

Android数据绑定在自定义视图中注入ViewModel

零安全的好处

调用单元测试验证伴随对象方法

Kotlin Android:属性委托必须有一个 'getValue(DashViewModel, KProperty*>)' 方法

如何启用spring security kotlin DSL?

将字符串转换为HashMap的最简单方法

尾随 lambda 语法(Kotlin)的目的是什么?

如何在 Kotlin 中定义新的运算符?