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) -> { //... }
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.
Unlike earlier version of Java8, Kotlin can have default implementation in interface.
A lambda expression is always surrounded by curly braces, argument declarations go inside curly braces and have optional type annotations, the code_body goes after an arrow -> sign. If the inferred return type of the lambda is not Unit, then the last expression inside the lambda body is treated as return value.
Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.
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) { //... } }
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 -> ... }
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