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?
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.
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.
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).
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.
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!") } })
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