7u4 / mapstruct-kotlin-builder-generator

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

mapstruct-kotlin-builder-generator

Library for generating builders for data classes, that are used in Mapstruct mappers as return types.

The problem

In Kotlin the following code produces 2 constructors from perspective of Java, default one and with a parameters:

data class Example(
    val prop1: String? = null,
    val prop2: String? = null
)

According to Mapstruct documentation, mapstruct always prefers a default constructor. And since properties declared as val, they cannot be reassigned.

There is known mapstruct issue #2378 and some possible workarounds:

  • you can use @Default annotation to mark non-empty constructor
  • mark properties as var so Mapstruct can reassign them
  • don't use default values in constructors
  • explicitly define default constructor as private

But such solutions will make your code a little messy. And sometimes you cannot apply any of these solutions, because your data classes are generated by third-party tools as dgs-codegen or jooq.

The solution

According to the documentation Mapstruct supports mapping of immutable types via builders, and you can implement your custom builder provider logic.

So my solution generates builders at compile time for data classes, that are used in Mapstruct mappers as return types.

Partly inspired by https://github.com/Pozo/mapstruct-kotlin.

The usage

First apply kapt plugin

plugins {
    id "org.jetbrains.kotlin.kapt" version "1.6.21"
}

Then add these to your project as dependency:

kapt("io.github.olxmute:mapstruct-kotlin-builder-generator:0.0.2")
ezoic increase your site revenue

About

License:MIT License


Languages

Language:Kotlin 100.0%