SAM conversions let you write simple Kotlin code when using Java interfaces with one method. It makes your code shorter and easier to read.
0
0
SAM conversions for Java interfaces in Kotlin
Introduction
When you want to pass a simple action to a Java method that expects an interface with one method.
When you use Java libraries that have interfaces like Runnable or Comparator.
When you want to write cleaner Kotlin code calling Java code without writing full classes.
When you want to quickly create a small behavior without extra boilerplate.
Syntax
Kotlin
val runnable = Runnable { println("Hello from SAM") } Thread(runnable).start()
You write a lambda instead of a full class implementing the interface.
This works only for Java interfaces with exactly one abstract method (SAM = Single Abstract Method).
Examples
Create a Runnable using a lambda and start a thread.
Kotlin
val runnable = Runnable { println("Run in thread") } Thread(runnable).start()
Create a Comparator with a lambda to sort strings by length.
Kotlin
val comparator = Comparator<String> { a, b -> a.length - b.length } val list = listOf("cat", "elephant", "dog") println(list.sortedWith(comparator))
Use SAM conversion to handle a button click event in Java Swing.
Kotlin
val action = java.awt.event.ActionListener { e -> println("Button clicked") } button.addActionListener(action)
Sample Program
This program shows how to use SAM conversions for Runnable and Comparator Java interfaces in Kotlin. It runs a thread and sorts a list.
Kotlin
fun main() { val runnable = Runnable { println("Hello from SAM conversion") } Thread(runnable).start() val comparator = Comparator<String> { a, b -> a.length - b.length } val words = listOf("apple", "banana", "kiwi") val sorted = words.sortedWith(comparator) println(sorted) }
OutputSuccess
Important Notes
SAM conversions only work with Java interfaces, not Kotlin interfaces.
Behind the scenes, Kotlin creates an object implementing the interface for you.
This feature helps keep Kotlin code concise when working with Java libraries.
Summary
SAM conversions let you use lambdas for Java interfaces with one method.
This makes Kotlin code shorter and easier when calling Java APIs.
Use it for Runnable, Comparator, listeners, and other single-method interfaces.