Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass interface as parameter in Kotlin

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?

like image 200
maphongba008 Avatar asked Jan 14 '17 11:01

maphongba008


People also ask

Can I pass a function as a parameter in Kotlin?

Kotlin gives us the power to declare high-order functions. In a high-order function, we can pass and return functions as parameters.

Can Kotlin data implement interface?

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.

How do I use Kotlin interface?

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.


2 Answers

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)

like image 75
Tomasz Czura Avatar answered Sep 21 '22 02:09

Tomasz Czura


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

like image 29
eliranno Avatar answered Sep 19 '22 02:09

eliranno