Lambda implementation of interface in kotlin

12,807

Solution 1

If AnInterface is Java, you can work with SAM conversion:

val impl = AnInterface { inst, num -> 
     //...
}

Otherwise, if the interface is Kotlin...

interface AnInterface {
     fun doSmth(inst: MyClass, num: Int)
}

...you can use the object syntax for implementing it anonymously:

val impl = object : AnInterface {
    override fun doSmth(inst:, num: Int) {
        //...
    }
}

Solution 2

If you're rewriting both the interface and its implementations to Kotlin, then you should just delete the interface and use a functional type:

val impl: (MyClass, Int) -> Unit = { inst, num -> ... }

Solution 3

You can use an object expression

So it would look something like this:

val impl = object : AnInterface {
    override fun(doSmth: Any, num: Int) {
        TODO()
    }
}
Share:
12,807
Jocky Doe
Author by

Jocky Doe

Updated on June 11, 2022

Comments

  • Jocky Doe
    Jocky Doe almost 2 years

    What would be the equivalent of that code in kotlin, nothing seems to work of what I try:

    public interface AnInterface {
        void doSmth(MyClass inst, int num);
    }
    

    init:

    AnInterface impl = (inst, num) -> {
        //...
    }