Konvert
Konvert is like Mapstruct for Kotlin. It is a kotlin compiler plugin using KSP API to generate kotlin code to map one class to another. It is open-source and available on GitHub.
There are three different ways to use Konvert:
Using
@KonvertTo
on source class:@KonvertTo(PersonDto::class) class Person(val firstName: String, val lastName: String) class PersonDto(val firstName: String, val lastName: String)
This will generate the following extension function
fun Person.toPersonDto(): PersonDto = PersonDto(firstName = firstName, lastName = lastName)
Using
@KonvertFrom
on target class (especially useful, if you cannot change the code of the source class)class Person(val firstName: String, val lastName: String) { @KonvertFrom(PersonDto::class) companion object } class PersonDto(val firstName: String, val lastName: String)
This will generate the following extension function
fun Person.Companion.fromPersonDto(personDto: PersonDto): Person = Person(firstName = personDto.firstName, lastName = personDto.lastName)
Using
@Konverter
on interfaces:class Person(val firstName: String, val lastName: String) class PersonDto(val firstName: String, val lastName: String) @Konverter interface PersonMapper { fun toDto(person: Person): PersonDto }
This will generate the following object
object PersonMapperImpl: PersonMapper { override fun toDto(person: Person): PersonDto = PersonDto(firstName = person.firstName, lastName = person.lastName) }
More information
See the documentation: https://mcarleio.github.io/konvert/