Java / MapStruct Java Interview questions part 2
What are default methods in a MapStruct mapper used for?
A default method inside a mapper interface lets you write custom conversion logic by hand for a specific type pair, while still leaving the rest of the mapping to MapStruct's generated code.
@Mapper public interface ProductMapper { ProductDto toDto(Product product); default String formatPrice(BigDecimal price) { return price == null ? "N/A" : "$" + price.setScale(2, RoundingMode.HALF_UP); } }
When a target property's type matches what a default method returns (and the parameter type matches the source), MapStruct automatically calls that method instead of trying to map the field itself, without any extra annotation.
More Related questions...