javamethodslambdainterfacekotlin

Lambda implementation of interface in kotlin


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) -> {
    //...
}

Solution

  • If AnInterface is Java, it can work with SAM conversion:

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

    Otherwise, if the interface is Kotlin:

    • Since Kotlin 1.4, it's possible to write functional interfaces :

      fun interface AnInterface {
           fun doSmth(inst: MyClass, num: Int)
      }
      val impl = AnInterface { inst, num -> ... }
      
    • Otherwise, if the interface is not functional

      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) {
              //...
          }
      }