https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Max Beyer

10/07/2020, 4:44 PM
greetings all, I’m wondering about initializing objects via a constructor vs an extension function. Example via constructor:
Copy code
data class CarDTO(
    val make: String,
    val model: String,
    val year: Int
)

data class Car(
    val make: String,
    val model: String,
    val year: Int
) {
    constructor(carDTO: CarDTO) : this(
        make = carDTO.make,
        model = carDTO.model,
        year = carDTO.year
    )
}
Example via extension function:
Copy code
data class CarDTO(
    val make: String,
    val model: String,
    val year: Int
) {
    fun toCar(): Car {
        return Car(
            make = this.make,
            model = this.model,
            year = this.year
        )
    }
}

data class Car(
    val make: String,
    val model: String,
    val year: Int
)
Is there an advantage to using one of these over the other? I’ve been doing some research, but can’t find any arguments either way.
t

Tobias Berger

10/07/2020, 4:50 PM
First of: you're not defining any extension function in your examples. You're just defining a regular function. I personally suggest actually defining an extension function on CarDTO, possibly even in another file. That keeps both data classes clean and independent of each other. Both (data) classes just have the purpose of storing information. Mapping between them is not their responsibility (separation of concerns).
👍 1
so that would be
Copy code
// CarDTO.kt
data class CarDTO(
    val make: String,
    val model: String,
    val year: Int
)

// CarMapping.kt
fun CarDTO.toCar() = Car(
    make = make,
    model = model,
    year = year
)

// Car.kt
data class Car(
    val make: String,
    val model: String,
    val year: Int
)
👍 1
💯 1
v

Vampire

10/07/2020, 4:56 PM
Will the second example (of OP) actually compile? I don't think so
No, it will not
t

Tobias Berger

10/07/2020, 4:58 PM
It won't, but I think the goal is clear
👍 2
m

Max Beyer

10/07/2020, 5:38 PM
Good catch @Vampire, you’re right, I’m missing a
return
(adding it now in an edit). The joys of blind coding outside of a compiler 🙂
I like that separation of concerns argument. Thanks!