Reputation: 11
I have a data class PersonRecord
. But the data I receive from an API has different form, I need to process it in order to extract A.
PersonForm
to represent the API-data and then create an independent function that take into parameters an instance of class PersonForm
and returns an instance of class PersonRecord
.Looking at some stackoverflow posts, I have also found the following solutions :
2.
data class PersonRecord(val name: String, val age: Int, val tel: String){
object ModelMapper {
fun from(form: PersonForm) =
PersonRecord(form.firstName + form.lastName, form.age, form.tel)
}
}
Is there a way that is more idiomatic/efficient/natural etc ? In which context, each one is preferred ?
Thanks.
Upvotes: 0
Views: 131
Reputation: 7882
The most idiomatic/natural way is creating secondary constructor:
data class PersonRecord(val name: String, val age: Int, val tel: String) {
constructor(form: PersonForm) : this(form.firstName + form.lastName, form.age, form.tel)
}
Upvotes: 1