DEV Community

Cover image for Functional Interfaces in Kotlin
Amr Hesham
Amr Hesham

Posted on

Functional Interfaces in Kotlin

Hello everyone, almost all of us have seen code like view.setOnClickListener { } or view.setOnLongClickListener { } in Kotlin, and when you click on it to see the source code it will show you the Java OnClickListener interface. But have you asked yourself what is this syntax? Is it a kotlin extension? and how can you call your custom listener like this? In this small article, you will know the answer to all of those questions, so let's start 😋.

This syntax is not an extension but SAM conversion, but what does SAM stand for?

SAM stands for Single Abstract Method interface and it’s called also Functional interface which is an interface with only one non-default method and any number of default methods, for examples In the JDK we have Runnable class which has only one method called run and in Android SDK we have OnClickListener, OnLongClickListener …etc.

How can we create a custom functional interface?

To declare a Functional interface in Java it is easy you just create a normal interface with one method for example.

public interface FunInterface {
    void method();
}
Enter fullscreen mode Exit fullscreen mode

And in Kotlin starting from Version 1.4 you need to declare it as a fun interface not only interface for example.

fun interface FunInterface {
    fun method()
}
Enter fullscreen mode Exit fullscreen mode

In Kotlin you can use Java or Kotlin Functional interfaces as a Lambda expression for example.

fun learnFunInterface(fi : FunInterface) { ... }
Enter fullscreen mode Exit fullscreen mode

To you this function you can pass FunInterface as an anonymous object for example.

learnFunInterface(object : FunInterface { 
    override fun method() {
        println("Hello") 
    } 
})
Enter fullscreen mode Exit fullscreen mode

But because it Functional Interface you can pass it as lambda { } and this is what is called SAM conversion.

learnFunInterface ({ println("Hello") })
Enter fullscreen mode Exit fullscreen mode

also in Kotlin if your last parameter is functional interface you can move your lambda out the brackets ( ) for example.

learnFunInterface {
    println("Hello")
}
Enter fullscreen mode Exit fullscreen mode

Now you can realize that setOnClickListener { } is just because this method takes functional interface which is OnClickListener as a parameter.

Note that the same syntax will work on Kotlin also if your functional interface is written in Java like OnClickListener.

Enjoy Programming 😋.

Top comments (0)