Functional or SAM interface in Kotlin

Akshay Shah
1 min readOct 30, 2021

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?

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Akshay Shah
Akshay Shah

Written by Akshay Shah

Lead Software Engineer @ EPAM Systems |Android | Kotlin | KMM

No responses yet

Write a response