RealmObject的Kotlin数据类 [英] Kotlin data class of RealmObject

查看:168
本文介绍了RealmObject的Kotlin数据类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Kotlin和Realm编写数据类

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)

我必须将数据保存到db,所以我使用Realm来保存它.但是据我们所知,如果我要将类保存到Realm,则AuthToken类必须扩展RealmObject.

I have to save the data to db, so I use Realm to save it. But as we know, if I want to save the class to Realm, the AuthToken class has to extend RealmObject.

这就是问题,Kotlin说数据类不能扩展类. 所以我放弃了数据类,只使用普通的Kotlin类作为模型,然后出现了另一个问题:

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类没有getter或setter.众所周知,Realm类必须将所有属性设置为私有,并编写getter和setter.

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中编写与Realm兼容的模型类的示例:

Realm doesn't support Data classes currently. You can see an example of how to write Realm compatible model classes in Kotlin here: 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() {

这篇关于RealmObject的Kotlin数据类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆