
Functional or SAM interface in Kotlin
We all have been using functional interfaces or as we also know them as SAM ( Single Abstract Method ) interfaces. Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
So what is a Functional or a SAM interface?
interface NewShape{
fun invoke(): Boolean
}
This is it! this is a functional or a SAM interface. Any interface which has a single abstract method would be a functional interface.
Such interfaces have been widely used across the Android ecosystem e.g OnClickListener, which has only one method i.e onClick().
So, how is it different in Kotlin?
The old or the traditional way of writing a functional or SAM interface is
interface OldWay{
fun invoke(): Boolean
}
so when you use this interface in Kotlin, it would look something like this
val old = object: OldWay {
override fun invoke(): Boolean = true
}
However, in Kotlin you would write them like this
fun interface NewWay{
fun invoke(): Boolean
}
and when you use them
val newSam = NewWay { true }
Concise, no boiler plate code, easily readable, ain’t it?