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?
Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters.
A class in Kotlin can implement as many interfaces as they like but it can only extend from one abstract class. Properties in the interface cannot maintain state, while they can in an abstract class.
The keyword “interface” is used to define an interface in Kotlin as shown in the following piece of code. In the above example, we have created one interface named as “ExampleInterface” and inside that we have a couple of abstract properties and methods all together.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With