Kotlin data class of RealmObject

房东的猫 提交于 2019-11-29 04:56:28

问题


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)

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.

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.


回答1:


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() {



回答2:


Any Kotlin property in any class has a getter and a setter. So I believe you code should just work as yourself suggested (without data modifier).

https://kotlinlang.org/docs/reference/data-classes.html#data-classes https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#properties

P.S. I agree that the docs on properties are unclear on the subject



来源:https://stackoverflow.com/questions/34368374/kotlin-data-class-of-realmobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!