0
0
Kotlinprogramming~15 mins

SAM conversions for Java interfaces in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
SAM conversions for Java interfaces in Kotlin
📖 Scenario: You are working on a Kotlin project that uses a Java interface with a single abstract method (SAM). You want to use Kotlin's SAM conversion feature to simplify your code by passing a lambda instead of an anonymous class.
🎯 Goal: Learn how to use SAM conversions in Kotlin to implement a Java interface with a single abstract method using a lambda expression.
📋 What You'll Learn
Create a Java interface with a single abstract method
Create a Kotlin variable to hold an instance of the Java interface
Use a lambda expression to implement the interface using SAM conversion
Print the result of calling the interface method
💡 Why This Matters
🌍 Real World
SAM conversions let Kotlin developers write concise code when working with Java libraries that use interfaces with a single method, such as event listeners or callbacks.
💼 Career
Understanding SAM conversions is important for Kotlin developers working in mixed Java-Kotlin codebases, improving code readability and reducing boilerplate.
Progress0 / 4 steps
1
Create the Java interface
Create a Java interface called Action with a single abstract method perform that returns a String.
Kotlin
Need a hint?

Remember, a Java interface with one method is a SAM interface.

2
Create a Kotlin variable for the interface
In Kotlin, create a variable called action of type Action and assign it null for now.
Kotlin
Need a hint?

Use val to declare a Kotlin variable and specify the type Action?.

3
Use SAM conversion with a lambda
Change the Kotlin variable action to use SAM conversion by assigning a lambda that returns the string "Action performed".
Kotlin
Need a hint?

Use Action { "Action performed" } to create the instance with SAM conversion.

4
Print the result of calling the interface method
Write a Kotlin println statement to print the result of calling perform() on the action variable.
Kotlin
Need a hint?

Call action.perform() inside println to display the message.