36

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.

Mibac
  • 8,990
  • 5
  • 33
  • 57
Allen Vork
  • 1,536
  • 3
  • 16
  • 29
  • I also experienced this issue with SugarORM....Jetbrains have asked for feedback on it... You can post cooments to this post though: http://blog.jetbrains.com/kotlin/2015/09/feedback-request-limitations-on-data-classes/ – Krupal Shah Dec 20 '15 at 08:31

2 Answers2

40

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() {
Christian Melchior
  • 19,978
  • 5
  • 62
  • 53
  • 2
    Do we have any update on this? In Realm 3.0.0 I see final fields are still not allowed (that's why you use open), but thus you lose those derived methods data classes automatically provide. – GoRoS Mar 17 '17 at 12:43
  • 5
    Data classes are fundamentally problematic since they essentially do what AutoValue does, so It is doubtful we can ever support data classes as RealmObjects. See e.g https://github.com/realm/realm-java/issues/4291 which describes our current thinking. (Search for AutoValue, it is a quite long text). – Christian Melchior Mar 17 '17 at 12:48
  • @GoRoS although the example code has been updated to remove the `open` modifier on kotlin properties, i think it's still necessary to keep them, because when they are accessed from Kotlin code, it seemed to still be getting the raw field value in some cases. – Eric May 12 '20 at 16:57
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

voddan
  • 31,956
  • 8
  • 77
  • 87