Kotlin SAM Conversions in Kotlin
Introduction
Kotlin SAM Conversions is a fundamental concept every Kotlin developer should understand. Kotlin and Java compile to the same JVM bytecode, so you can mix both languages in one project with minimal friction.
SAM conversion allows lambda where Java functional interface is expected. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- SAM conversion allows lambda where Java functional interface is expected.
- Kotlin fun interfaces also support SAM conversion.
- Reduces boilerplate for single-method interfaces.
Syntax
button.setOnClickListener { }Kotlin SAM Conversions in Kotlin Example Program in Kotlin
fun interface ClickHandler {
fun onClick()
}
fun register(handler: ClickHandler) {
handler.onClick()
}
fun main(args: Array<String>) {
register { println("Button clicked via SAM conversion") }
}Sample Output
Button clicked via SAM conversionWhen to use
Use interop when migrating a Java codebase incrementally or calling mature Java libraries from Kotlin.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
The
println("Button clicked via SAM conversion")statement writes a line to the console — this produces part of the sample output below. -
SAM conversion allows lambda where Java functional interface is expected.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- SAM conversion allows lambda where Java functional interface is expected.
- Kotlin fun interfaces also support SAM conversion.
- Reduces boilerplate for single-method interfaces.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Nullability annotations help Kotlin and Java agree on which values can be null at boundaries.
- Semicolons at the end of statements are optional in Kotlin.