Reputation: 2259
I have two constructors in my Kotlin object, a primary and a secondary. The primary has nothing in it and the secondary takes some parameters. I would like to map a DTO in the secondary constructor, but I don't see what is the problem.
Example
open class User(): RealmObject() {
@PrimaryKey
open var id: Long = 0
open var login: String? = null
open var firstName: String? = null
open var surname: String? = null
open var isAdmin: Boolean = false
open var groups: RealmList<Int>? = null
constructor(id: Long?, login: String?, firstName: String?, surname: String?, admin: Boolean?, groups: List<Int>?) : this()
companion object {
fun map(dto: UserDTO): User {
Timber.d(dto.toString()) //The response data from the WS, OK with some data
val groups = RealmList<Int>()
dto.groups?.forEach { groups.add(it) }
val u = User(dto.id, dto.login, dto.firstName, dto.surname, dto.admin, groups) //Calling the secondary constructor
Timber.d(u.toString()) // Everything is null or false, KO
return u
}
}
}
Upvotes: 1
Views: 578
Reputation: 8870
A couple of things look a little off. You're calling your primary constructor's "this" with no arguments, and not setting the passed in values in the secondary either; since they aren't declared inline on the constructor as val
or var
so they won't stick around after the constructor finishes.
A better approach here would be to just use one constructor declare all your val/vars in the constructor rather than the class body, and provide default initialization values. This way, you can use named arguments for construction, which negates the need for multiple in this case.
Ex:
open class SomeClass(@PrimaryKey
open var id: Long = 0,
open var login: String? = null,
open var firstName: String? = null,
open var surname: String? = null,
open var isAdmin: Boolean = false,
open var groups: RealmList<Int>? = null): RealmObject()
Upvotes: 1