Pass interface as parameter in Kotlin

2019-04-18 07:15发布

问题:

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?

回答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)