SAM interface conversion in Kotlin 1.4
Kotlin 1.4 has just been released. The update includes a convenience syntax for SAM (Single Abstract Method) conversion.
Let's take a look at the code.
Before 1.4, when we have a SAM interface:
fun main() {
// before Kotlin 1.4
testing(object: Callback {
override fun doStuff() {
println("Hello, world!!!")
}
})
}
fun testing(callback: Callback) {
callback.doStuff()
}
interface Callback {
fun doStuff()
}
Link to Kotlin Playground: pre-kotlin1_4.kt
After upgrading to Kotlin 1.4, we can simplify it like this:
fun main() {
// after Kotlin 1.4+
testing {
println("Hello, world!!!")
}
}
fun testing(callback: Callback) {
callback.doStuff()
}
fun interface Callback { /* <---- add the fun keyword here */
fun doStuff()
}
Link to Kotlin Playground: after-upgrading-to-kotlin1_4.kt
Note: we will have to add the fun
keyword in front of the interface
otherwise it will not work.
Bonus Tip: Android Studio
If you are using this in Android Studio and have already upgraded to 1.4 but still getting red underline, you will need to update the Kotlin version in the IDE for it to work. Here are the 2 changes that you need.
1. adding in app/build.gradle
android {
compileOptions {
kotlinOptions {
+ languageVersion = "1.4"
}
}
}
2. Change the Kotlin version in Preference/Settings
After changing these settings, the red underline should go away when on this line:
fun interface Callback { <----
fun doStuff()
}
That's all for now, thanks for reading! ☕️
Clap to support the author, help others find it, and make your opinion count.