DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Originally published at sanjayprajapat.hashnode.dev

3 1

Functional (SAM) interfaces in Kotlin

An interface with only one abstract method is called a functional interface(Single Abstract Method). functional (SAM) interface can have multiple non abstract method but only one abstract method

// functional interface example
interface CatchAble {
    fun invoke()
}
Enter fullscreen mode Exit fullscreen mode

SAM conversions

Instead of creating a class that implements a functional interface manually, you can use a lambda expression.

// functional interface example
interface CatchAble {
    fun invoke()
}

// functional interface example
fun interface FunctInterface{
    fun invoke(list: List<Int>) :List<Int>
}

// functional interface
interface FuncInterface3 {
    fun abstract_method(a: Int, b: String?)
    // Second method prevents lambda conversion
    fun   nonabstract_method() {
        println("do something")
    }
}


Enter fullscreen mode Exit fullscreen mode
fun main(){

    // if we don't use SAM conversion
    val run  = object : CatchAble {
        override fun invoke() {
            print("Invoking CatchAble ")

        }
    }
    run.invoke() //  // Invoking CatchAble

    // if don't SAM use SAM conversion
    val fi = object :FunctInterface{
        override fun invoke(list: List<Int>): List<Int> {
            return  list.filter { pre -> pre %2 ==0 }
        }
    }
    print(fi.invoke(listOf(2,5,1,5,79,0))) // [2, 0]

    // using same conversion
    val fi2 = FunctInterface {
        it.filter { pre -> pre %2 == 0 }
    }
    print(fi2.invoke(listOf(2,5,1,5,79,0))) // [2, 0]

val fi3 = object : FuncInterface3{
        override fun abstract_method(a: Int, b: String?) {
            print("This is abstract method")
        }

        // it's not force to override this method
        override fun nonabstract_method() {
            print("overriding non abstract method")
        }
    }

    fi3.nonabstract_method() // do something
    fi3.abstract_method(2,"323") //overriding non-abstract method
}
Enter fullscreen mode Exit fullscreen mode

Functional (SAM) interfaces in Java

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay