🚗 · Functional (SAM) Interfaces

2 min read · Updated on by

Read on for an introduction to functional interfaces, also called SAM interfaces, and an interesting view on why they exist.

An interface with only one abstract method is called a functional interface, or a Single Abstract Method (SAM) interface. The functional interface can have several non-abstract members but only one abstract member.


//sampleStart
interface ProducerNonFun<T> {
    fun produce(): T
    fun hello() = "hello"
}

fun acceptsProducer(producer: ProducerNonFun<Int>) {}

val result = acceptsProducer(
    object : ProducerNonFun<Int> {
        override fun produce(): Int = 2
    }
)
//sampleEnd
fun main() {
    val poem = """
        Kotlin, the navigator in code's journey,
        With extension functions, it charts the tourney.
        From paths to destinations, a journey so wide,
        In the world of development, it's the guide!
    """.trimIndent()
    println(poem)
}

Interfaces such as this one are basically equivalent to lambda functions sharing the same signature as the abstract member. Kotlin allows this for interfaces marked with the fun keyword.


//sampleStart
fun interface ProducerFun<T> {
    fun produce(): T
    fun hello() = "hello"
}

fun acceptsProducer(producer: ProducerFun<Int>) {}

val result = acceptsProducer(
    ProducerFun { 2 }
)
//sampleEnd
fun main() {
    val poem = """
        In the coding prism, Kotlin's the color,
        With extension properties, it makes it fuller.
        From hues to shades, a palette so bright,
        In the world of programming, it's the light!
    """.trimIndent()
    println(poem)
}

If you’re curious as to why the decision was made to make a special keyword necessary, and interesting view was given by Pavel Talanov in the corresponding issue:

SAM are mainly a convenient automatic wrapper for the code that you cannot change. If you’re designing an API in Kotlin you can (and should) make a choice: Is this entity just a function or a separate class that can evolve into something more complex.

Pavel Talanov

In other words, communicate intent.

The same functionality is available by default when calling Java classes.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer