Kotlin: Better way to map Kotlin data objects to data objects

Kotlin Programming

Question or issue of Kotlin Programming:

I want to convert/map some “data” class objects to similar “data” class objects. For example, classes for web form to classes for database records.

data class PersonForm(
    val firstName: String,
    val lastName: String,
    val age: Int,
    // maybe many fields exist here like address, card number, etc.
    val tel: String
// maps to ...
data class PersonRecord(
    val name: String, // "${firstName} ${lastName}"
    val age: Int, // copy of age
    // maybe many fields exist here like address, card number, etc.
    val tel: String // copy of tel

I use ModelMapper for such works in Java, but it can’t be used because data classes are final (ModelMapper creates CGLib proxies to read mapping definitions). We can use ModelMapper when we make these classes/fields open, but we must implement features of “data” class manually.
(cf. ModelMapper examples: https://github.com/jhalterman/modelmapper/blob/master/examples/src/main/java/org/modelmapper/gettingstarted/GettingStartedExample.java)

How to map such “data” objects in Kotlin?

ModelMapper automatically maps fields that have same name (like tel -> tel) without mapping declarations. I want to do it with data class of Kotlin.

The purpose of each classes depends on what kind of application, but these are probably placed in the different layer of an application.

For example:

These classes are similar, but are not the same.

I want to avoid normal function calls for these reasons:

Of course, a library that has similar feature is intended, but information of the Kotlin feature is also welcome (like spreading in ECMAScript).

How to solve this issue?

Solution no. 1:

  1. Simplest (best?):

    fun PersonForm.toPersonRecord() = PersonRecord( name = "$firstName $lastName", age = age, tel = tel ) 
  2. Reflection (not great performance):

    fun PersonForm.toPersonRecord() = with(PersonRecord::class.primaryConstructor!!) { val propertiesByName = PersonForm::class.memberProperties.associateBy { it.name } callBy(args = parameters.associate { parameter -> parameter to when (parameter.name) { "name" -> "$firstName $lastName" else -> propertiesByName[parameter.name]?.get(this@toPersonRecord) } }) } 
  3. Cached reflection (okay performance but not as fast as #1):

    open class Transformer<in T : Any, out R : Any> protected constructor(inClass: KClass<T>, outClass: KClass<R>) { private val outConstructor = outClass.primaryConstructor!! private val inPropertiesByName by lazy { inClass.memberProperties.associateBy { it.name } } fun transform(data: T): R = with(outConstructor) { callBy(parameters.associate { parameter -> parameter to argFor(parameter, data) }) } open fun argFor(parameter: KParameter, data: T): Any? { return inPropertiesByName[parameter.name]?.get(data) } } val personFormToPersonRecordTransformer = object : Transformer<PersonForm, PersonRecord>(PersonForm::class, PersonRecord::class) { override fun argFor(parameter: KParameter, data: PersonForm): Any? { return when (parameter.name) { "name" -> with(data) { "$firstName $lastName" } else -> super.argFor(parameter, data) } } } fun PersonForm.toPersonRecord() = personFormToPersonRecordTransformer.transform(this) 
  4. Storing Properties in a Map

    data class PersonForm(val map: Map<String, Any?>) { val firstName: String by map val lastName: String by map val age: Int by map // maybe many fields exist here like address, card number, etc. val tel: String by map } // maps to ... data class PersonRecord(val map: Map<String, Any?>) { val name: String by map // "${firstName} ${lastName}" val age: Int by map // copy of age // maybe many fields exist here like address, card number, etc. val tel: String by map // copy of tel } fun PersonForm.toPersonRecord() = PersonRecord(HashMap(map).apply { this["name"] = "${remove("firstName")} ${remove("lastName")}" }) 

Solution no. 2:

Is this are you looking for?

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)           

and then:

val personRecord = PersonRecord.ModelMapper.from(personForm)

Solution no. 3:

MapStruct lets kapt generate classes doing the mapping (without reflection).

Use MapStruct:

interface PersonConverter {

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

    fun convertToModel(personDto: PersonDto) : Person


// Note this either needs empty constructor or we need @KotlinBuilder as dsecribe below
data class Person: this(null, null, null, null) (...)


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)

val personModel = converter.convertToModel(personDto)


Now with @KotlinBuilder for avoiding constructor() issue:

GitHub: Pozo’s mapstruct-kotlin

Annotate data classes with @KotlinBuilder. This will create a PersonBuilder class, which MapStruct uses, thus we avoid ruining the interface of the data class with a constructor().

data class Person(
    val firstName: String,
    val lastName: String,
    val age: Int,
    val tel: String

Dependency :

// https://mvnrepository.com/artifact/com.github.pozo/mapstruct-kotlin


Solution no. 4:

Do you really want a separate class for that? You can add properties to the original data class:

data class PersonForm(
    val firstName: String,
    val lastName: String,
    val age: Int,
    val tel: String
) {
    val name = "${firstName} ${lastName}"

Solution no. 5:

Using ModelMapper

/** Util.kt **/

class MapperDto() : ModelMapper() {
    init {
        configuration.matchingStrategy = MatchingStrategies.LOOSE
        configuration.fieldAccessLevel = Configuration.AccessLevel.PRIVATE
        configuration.isFieldMatchingEnabled = true
        configuration.isSkipNullEnabled = true

object Mapper {
    val mapper = MapperDto()

    inline fun  convert(source: S): T = mapper.map(source, T::class.java) } 


val form = PersonForm(/** ... **/) val record: PersonRecord = Mapper.convert(form) 

You might need some mapping rules if the field names differ. See the getting started
PS: Use kotlin no-args plugin for having default no-arg constructor with your data classes

Solution no. 6:

This works using Gson:

inline fun Any.mapTo(): T = GsonBuilder().create().run { toJson([email protected]).let { fromJson(it, T::class.java) } } fun PersonForm.toRecord(): PersonRecord = mapTo().copy( name = "$firstName $lastName" ) fun PersonRecord.toForm(): PersonForm = mapTo().copy( firstName = name.split(" ").first(), lastName = name.split(" ").last() ) 

with not nullable values allowed to be null because Gson uses sun.misc.Unsafe..

Solution no. 7:

You can use ModelMapper to map to a Kotlin data class. The keys are:

  • Use @JvmOverloads (generates a constructor with no arguments)
  • Default values for data class member
  • Mutable member, var instead of val

    data class AppSyncEvent @JvmOverloads constructor( var field: String = "", var arguments: Map<String, *> = mapOf<String, Any>(), var source: Map<String, *> = mapOf<String, Any>() ) val event = ModelMapper().map(request, AppSyncEvent::class.java) 

Solution no. 8:

For ModelMapper you could use Kotlin’s no-arg compiler plugin, with which you can create an annotation that marks your data class to get a synthetic no-arg constructor for libraries that use reflection. Your data class needs to use var instead of val.

package com.example

annotation class NoArg

data class MyData(var myDatum: String)

mm.map(. . ., MyData::class.java)

and in build.gradle (see docs for Maven):

buildscript {
  . . .
  dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"

apply plugin: 'kotlin-noarg'

noArg {
  annotation "com.example.NoArg"

Hope this helps!