Pass interface as parameter in Kotlin Pass interface as parameter in Kotlin android android

Pass interface as parameter in Kotlin


In Kotlin you can do :

test(object: Handler {    override fun onComplete() {    }})

Or make a property the same way:

val handler = object: Handler {    override fun onComplete() {    }}

And, somewhere in code: test(handler)


since your interface has only one function. you can convert it to SAM like this

fun interface Handler {        fun onCompleted()}

then you can just implement this interface using lambda instead and so reduce the overall written code. this is only possible in v1.4


Attached is an example of how to pass an object by parameter that represents the value of the data type and invoke behaviors using interface inheritance.

fun main() {    val customClass = CustomClass(            object : First {                override fun first() {                    super.first()                    println("first new impl")                }                override fun second() {                    super.second()                    println("second new impl")                }            }    )    customClass.first.first()    customClass.first.second()}data class CustomClass(val first: First)interface First: Second {    fun first() {        println("first default impl")    }}interface Second {    fun second() {        println("second default impl")    }}

It is worth mentioning that with super.first() or super.second() the default behavior of the interface is being invoked.

It doesn't make much sense to pass a lamda with an anonymous object as a parameter, lambda: () -> Unit , if what we need is to invoke the functions.

GL

Playground