Pass interface as parameter in Kotlin

22,823

Solution 1

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)

Solution 2

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

Share:
22,823
maphongba008
Author by

maphongba008

Updated on January 19, 2021

Comments

  • maphongba008
    maphongba008 over 3 years

    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?