I have two entities with the same properties (one ...
# announcements
p
I have two entities with the same properties (one is basically a DTO) an I want to create the DTO from the Entity. Something comparable to:
Copy code
class EmployeeModel(val id: Long, val firstName: String, val lastName: String)
class Employee(val id: Long, val firstName: String, val lastName: String)
is there a more idiomatic way of creating one object from the other than:
Copy code
EmployeeModel(employee.id, employee.firstName, employee.lastName)
Thank you!
p
I typically just add a secondary constructor that takes the second object like…
Copy code
class EmployeeModel(val id: Long, val firstName: String, val lastName: String) {
    constructor(employee: Employee) : this(employee.id, employee.firstName, employee.lastName)
}
p
Great, exactly what I was looking for. I'm suprised that didn't come up to my mind. Thank you!
d
I would not add that second constructor as it creates a hard coupling between the classes. Will get back with my own suggestion soon.
p
If I'm not missing something I think that's not a problem in this scenario since the EmployeeModel is basically just a DTO for HATEOAS. Besides that it would be nice to see your solution!
d
Copy code
val model = with(employee) {
  EmployeeModel(id, firstName, lastName)
}
or
Copy code
val model = employee.run {
  EmployeeModel(id, firstName, lastName)
}
or as extension function:
Copy code
fun Employee.toModel()  = EmployeeModel(id, firstName, lastName)
// ...
val model = emplyee.toModel()
(not tested code, at the wrong computer now)
c
great suggestions