Decorators
Decorate mapping operations with additional logic.
In some use cases mapping fields is not enough. Sometimes we need to add additional logic to the mapping. For these use cases we have the decorators, the decorators allow us to perform operations on our models after the mapping has finished.
We start with our two classes, our source class User
and our destination class UserDisplay
.
data class User(
var firstName: String,
var lastName: String
)
data class UserDisplay(
var firstName: String,
var lastName: String,
var fullName: String
)
In this example, we want to merge the firstName
and lastName
fields to the fullName
field.
Adding Decorators
Adding decorators is available through the ShapeShiftBuilder
class. Decorators can be added inline or as a separate class.
Class Decorators
To create a decorator class implement the MappingDecorator
interface.
class UserUserDisplayDecorator : MappingDecorator<User, UserDisplay> {
override fun decorate(context: MappingDecoratorContext<User, UserDisplay>) {
val (from, to) = context
to.fullName = "${from.firstName} ${from.lastName}"
}
}
And register it to the ShapeShift
instance.
val shapeShift = ShapeShiftBuilder()
.withDecorator(UserUserDisplayDecorator())
.build()
Inline Decorators
It is also possible to add the decorator logic inline.
val shapeShift = ShapeShiftBuilder()
.withDecorator(MappingDecorator<User, UserDisplay> {
val (from, to) = it
to.fullName = "${from.firstName} ${from.lastName}"
})
.build()
Last updated
Was this helpful?