Thursday, 20 November 2025

Kotlin: Redundant SAM constructor

Kotlin lambdas are fully compatible with Java functional interfaces.

But sometimes you need to give Kotlin a little nudge, using a SAM constructor.

SAM constructors (Single Abstract Method) allow you to convert a lambda expression to an instance of a functional interface. The syntax is pretty straightforward.

FunctionalInterfaceName { lambda_function }

The message in the title appears when you use a SAM constructor, when you don't have to. Kotlin is smart enough to create the appropriate anonymous class without us being specific in most cases.

I notice this happening sometimes when I have IntelliJ convert my Java class automatically to Kotlin.

A simple example:

// Java
public Builder addMapping(FieldMetadata field, Supplier<?> valueSupplier) {...}
// redundant Kotlin
val fieldMapping = FieldMapping.builder()
.addMapping(OrderItemField.ITEM_NR), Supplier { orderRepository.getOrderItem })
.build()
// correct Kotlin
val fieldMapping = FieldMapping.builder()
.addMapping(OrderItemField.ITEM_NR) { orderRepository.getOrderItem }
.build()

References

Medium - Idiomatic Kotlin: Lambdas and SAM constructors
https://medium.com/tompee/idiomatic-kotlin-lambdas-and-sam-constructors-fe2075965bfb

No comments:

Post a Comment