Lambda implementation of interface in kotlin

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

Leave a Comment

tech