ParkCheolu
ParkCheolu

Reputation: 1275

In Kotlin, are there graceful ways of passing values from one instance to another, which have the same name?

I have the following classes

class A(
  val value1: String,
  val value2: String,
  val value3: String,
  val value4: String,
  val value5: String,
)

class B(
  val value1: String,
  val value2: String,
  val value3: String,
  val value4: String,
  val value5: String,
) {

  compaion object {
    from(a: A) = B(
      value1 = a.value1,
      value2 = a.value2,
      value3 = a.value3,
      value4 = a.value4,
      value5 = a.value5,
    )
  }
}

I write codes as follows when I want to create an instance of B from A

val a: A = getAFromSomewhere()
val b: B = B.from(a)

I have a lot of codes as above and It's very boring for me to write the factory method, 'from'. Is there any easy way of writing this kind of codes in Kotlin??

Upvotes: 0

Views: 71

Answers (1)

Pemassi
Pemassi

Reputation: 632

You might be interested in the MapStruct library.

https://mapstruct.org/

It helps map between two objects(DTO, Entity, etc..).

Code

In this example we want to map between a Person (Model) and a PersonDto (DTO).

data class Person(var firstName: String?, var lastName: String?, var phoneNumber: String?, var birthdate: LocalDate?)
data class PersonDto(var firstName: String?, var lastName: String?, var phone: String?, var birthdate: LocalDate?)

The MapStruct converter:

@Mapper
interface PersonConverter {

    @Mapping(source = "phoneNumber", target = "phone")
    fun convertToDto(person: Person) : PersonDto

    @InheritInverseConfiguration
    fun convertToModel(personDto: PersonDto) : Person

}

Usage:

val converter = Mappers.getMapper(PersonConverter::class.java) // or PersonConverterImpl()

val person = Person("Samuel", "Jackson", "0123 334466", LocalDate.of(1948, 12, 21))

val personDto = converter.convertToDto(person)
println(personDto)

val personModel = converter.convertToModel(personDto)
println(personModel)

From: https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-kotlin

Upvotes: 4

Related Questions