Approximations
Approximations

Reputation: 11

Difference between object and companion object and how to test them

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.

  1. The first solution consist of creating a data class 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)           
    }
}
  1. Same as two but with companion object instead of object.

Is there a way that is more idiomatic/efficient/natural etc ? In which context, each one is preferred ?

Thanks.

Upvotes: 0

Views: 131

Answers (1)

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

Related Questions