Hi all... I'm playing with kotlin and spring, I co...
# server
v
Hi all... I'm playing with kotlin and spring, I come from java/spring. I'm trying to figure out best way to create mappers. I found extensions could be quite usefull in this cases. But it seams I'm missing something. Can someone tell me why this works:
Copy code
class MyMapper {

    companion object AccountMapper {
        fun Account.toDto() = AccountDto(
            id, firstName, lastName, username, email, password, role, createdAt, lastModified,null
        )
        fun AccountDto.toEntity() = Account(
            id, firstName, lastName, username, email, password, role, createdAt, lastModified
        )
    }
}
And without companion object (if I just delete "companion object AccountMapper" and leave functions) ... it does not? Of course if there are some recomendations about how to handle mapping, please share.
k
The companion object makes them all static methods. You probably want to move them out of the class.
r
Has anyone tried konvert? https://github.com/mcarleio/konvert
a
@Vedran You do not need a Class nor a companion object. Just a Kotlin File with something like:
Copy code
package com.tempest.fuels.dbservices.mapper

import com.example.dto.CompanyDto
import com.example.domain.Company
import java.time.ZoneId
import java.util.*

fun Company.toDto(): CompanyDto =
  CompanyDto(
    extId = this.extId.toString(),
    name = this.name,
    description = this.description,
    createdAt = this.createdAt.atZone(ZoneId.of("UTC")),
    updatedAt = this.updatedAt.atZone(ZoneId.of("UTC"))
  )

fun CompanyDto.toEntity(): Company =
  Company(
    name = this.name,
    description = this.description,
    createdAt = this.createdAt.toLocalDateTime(),
    updatedAt = this.updatedAt.toLocalDateTime()
  ).also { e -> e.enabled = this.enabled; e.extId = UUID.fromString(this.extId) }

fun List<Company>.toDto(): List<CompanyDto> =
  this.map { it.toDto() }

fun List<CompanyDto>.toEntities(): List<Company> =
  this.map { it.toEntity() }
☝️ 2
I've not tried Konvert, but I have, in the past, used reflection/introspection to automate the mapping - but I prefer hand-written Mappers because occasionally useful to alter the Normalization level in the DTO vs the Entity levels. It's rare to do this, but it's useful - and once you've used an "automated" mapper it's painful to deal with exceptions
a
I do the same as @ashmelev does. I too have tried automated mappers before (both reflective and generated), and always find the gotchas and exceptions too much of a hassle to be worth it.
r
@ashmelev @Andrew O'Hara I'm not sure about Konvert because I haven't tested it yet. But with Map Struct, if I understood it correctly, this can be achieved with @AfterMapping. However, if those are simple mappers, then an automated one wouldnt be ideal indeed
v
thank you... Im not used to not having classes... It never crossed my mind....
a
@Vedran Welcome to Kotlin!! 🙂
K 3