Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin data class of RealmObject

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.

like image 730
Allen Vork Avatar asked Dec 19 '15 07:12

Allen Vork


People also ask

When should I use Kotlin data class?

Answer: Kotlin provides a special type of class called data class, which is usually used for objects that act as a store for data properties and has no business logic or member functions. It provides a lot of advantages with reduced boilerplate code.

How do you get data from Kotlin data class?

data class User(val name: String, val age: Int) fun main(args: Array<String>) { val u1 = User("John", 29) val u2 = u1. copy() val u3 = u1. copy(name = "Amanda") println("u1 hashcode = ${u1. hashCode()}") println("u2 hashcode = ${u2.

Can Kotlin data class have methods?

Data classes specialize in holding data. The Kotlin compiler automatically generates the following functionality for them: A correct, complete, and readable toString() method. Value equality-based equals() and hashCode() methods.

Can data class be abstract Kotlin?

Data classes cannot be abstract, open, sealed, or inner.


1 Answers

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() { 
like image 65
Christian Melchior Avatar answered Sep 21 '22 05:09

Christian Melchior