0

I am working with more complex classes so I try put there simple example what I need.

I have this interface:

interface BaseUser {
    val firstName: String
    val lastName: String
}

and these 2 data classes:

data class UserA(
    override val firstName: String,
    override val lastName: String,
): BaseUser

data class UserB(
    override val firstName: String,
    override val lastName: String,
    val someComputedProperty: Int
): BaseUser

I already wrote mapper to map a database entity User into UserA, something like that:

fun UserEntity.toDto(): UserA {
    return UserA(firstName = firstName, lastName = lastName)
}

I also need have similar method which map database entity to UserB and also compute value for aditional property. In real code I have a lot of properties in classes not just 2, so I am thinking how to reuse code, and use this mapping for UserB in some way, and also be able compute then from entity additional fields.

Is in Kotlin any elegant way to covert UserA into UserB thanks to interface or something else? Thank you.

Denis Stephanov
  • 4,563
  • 24
  • 78
  • 174
  • There's no elegant shorter way to do that. If `someComputedProperty` is based only on the other two properties, I don't think it should be in a data class constructor because then it will become wrong when you use the `copy` function, and it would be redundantly included in equals/hashcode. – Tenfour04 Jan 17 '23 at 14:36

1 Answers1

0

Although both data classes are implementing the same interface class, there is no built-in function to directly convert these classes directly. Because there is actually no relationship between data classes implementing the same interface class.

In order to convert one class to another, you can probably refer to this previous post.

Enowneb
  • 943
  • 1
  • 2
  • 11