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

Thursday, 13 November 2025

Rename .java to .kt

So, I've suddenly recently noticed that whenever I commit a change into Git in IntelliJ that contains a conversion of a .java file into a .kt (Kotlin) file, IntelliJ will automatically make a previous commit containing the comment "Rename .java to .kt" which contains ONLY the renaming of the file.

I thought this was odd, but the reason behind it is that this commit helps Git to bind the two files together in the History.

If you do not have this single commit, (for example, if you're merging this to your integration branch or whatever and you squash your commits), you lose the history. It means Git will see the .java file as a file that has been deleted and the .kt file as a new file that has been added.

Some people complain, but it really depends on what is important to you:

  • do you want to preserve your history in Git for a file
  • or
  • do you want to see the changing the filename as belonging to your commit (and your ticketnumber in de comments)

Ideally, you should bear in mind IntelliJ does this, so you can at least edit the Commit Message of the renaming to include your ticketnr and original comment and such.

Settings

Can you turn this setting off? Yes, you can. There's a checkbox in the settings of the Git Commit dialog.

Unfortunately, this interesting setting only appears when you have indeed converted a Java file into a Kotlin file.

References

Kotlinlang - slack-chats
https://slack-chats.kotlinlang.org/t/465094/hi-i-ve-discovered-to-my-surprise-that-the-java-to-kotlin-co