Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expressions in Kotlin

Consider the following Java class:

public class SomeClass {     public interface Something {         void doSomething();     }      public void call(Something something) {} } 

In Kotlin, I can use a lambda expression as follows:

SomeClass().call {      // do something } 

But if I define the following method in Kotlin (using the same interface):

fun call(something: Something) {} 

Then this call:

call {     // do something } 

Would generate a type mismatch error. Why?

like image 468
cdroid Avatar asked Oct 22 '14 12:10

cdroid


People also ask

What are lambda expressions in Kotlin?

Lambda expression is a simplified representation of a function. It can be passed as a parameter, stored in a variable or even returned as a value. Note: If you are new to Android app development or just getting started, you should get a head start from Kotlin for Android: An Introduction.

What is the type of a lambda in Kotlin?

Type Inference. Kotlin's type inference allows the type of a lambda to be evaluated by the compiler. Kotlin will understand that this lambda is of type (Int) -> String.

Does lambda support Kotlin?

AWS Lambda does not support serializing JSON objects into Kotlin data classes, but don't worry! AWS Lambda supports passing an input object as a Stream, and also supports an output Stream for returning a result (see this link for more information).


2 Answers

Kotlin only supports SAM conversions for Java methods, because Kotlin itself has function types. Normally, Kotlin functions should be taking () -> Unit rather than Something. If you really need it to take Something, you can use a SAM constructor:

call(Something { /* do something */ }) 

Any SAM type (Java interface with one abstract method) automatically gets such a constructor function that converts a lambda to its instance.

like image 182
Andrey Breslav Avatar answered Oct 13 '22 20:10

Andrey Breslav


Kotlin requires that call takes something of interface something.

() -> Kotlin.Unit 

Does not satisfy the type requirement.

You can do this

call (object : Something {     override fun doSomething() {         println("Passing an interface to call in kotlin!")     } }) 
like image 21
Jakob Bowyer Avatar answered Oct 13 '22 21:10

Jakob Bowyer