35
votes

I want to pass an interface as parameter like this:

class Test {
    fun main() {
        test({})
        // how can I pass here?
    }

    fun test(handler: Handler) {
        // do something
    }

    interface Handler {
        fun onCompleted()
    }
}

In Java, I can use anonymous function like test(new Handler() { .......... }), but I can't do this in Kotlin. Anyone know how to do this?

3

3 Answers

93
votes

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)

4
votes

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

-1
votes

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