首页 > 解决方案 > kotlin 中的 Mapstruct @Mapping(expression="...")

问题描述

是否可以在@Mapping注释中表达 Kotlin 表达式?

(简化的)问题如下:

我有这个数据类:

data class Data (
    val myClass: MyClass
)

和:

data class DataDto (
    myString: String
)

fun String.toMyClass() = ...

目前我想做这样的事情:

@Mapper
interface RefDataMapper {

    @Mapping(expression = "kotlin(myString?.toMyClass())", target = "myClass")
    fun toDomain(dataDto: DataDto) : Data

}

目前似乎表达式只能用 Java 编写,因此上述解决方案不起作用。有可能做我想做的事吗?

注意我不能使用装饰器,因为在Data类中这个属性是val这样设置的,我只能在实例化期间设置这个属性。

标签: kotlinmapstruct

解决方案


MapStruct does not have Kotlin expression support because MapStruct is only capable of generating Java code currently. Therefore, even if you mappers are defined in Kotlin the mapper implementation will be written in Java.

You will have to adapt your expression to use the java(...) format.


推荐阅读