Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) -> {     //... } 
like image 888
Jocky Doe Avatar asked Jan 16 '18 15:01

Jocky Doe


People also ask

How does Kotlin implement 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.

Can a function implement an interface Kotlin?

Unlike earlier version of Java8, Kotlin can have default implementation in interface.

How do you use lambda in Kotlin?

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.

What is lambda expression What are function interface and how we implement?

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.


2 Answers

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) {         //...     } } 
like image 147
s1m0nw1 Avatar answered Sep 28 '22 01:09

s1m0nw1


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 -> ... } 
like image 39
Marko Topolnik Avatar answered Sep 28 '22 01:09

Marko Topolnik