I have created an interface:
interface ProgressListener {
fun transferred(bytesUploaded: Long)
}
but can use it only as anonymous class, not lambda
dataManager.createAndSubmitSendIt(title, message,
object : ProgressListener {
override fun transferred(bytesUploaded: Long) {
System.out.println(bytesUploaded.toString())
}
})
I think it should be a possibility to replace it by lambda:
dataManager.createAndSubmitSendIt(title, message, {System.out.println(it.toString())})
But I am getting error: Type mismatch; required - ProgressListener, found - () -> Unit?
What am I doing wrong?
Kotlin only supports SAM conversions for Java interfaces.
-- Official documentation
If you want to use a lambda in the parameter, make your function take a function parameter instead of an interface. (For now at least. Supporting SAM conversions for Kotlin interfaces is an ongoing discussion, it was one of the possible future features at the Kotlin 1.1 live stream.)
A little late to the party: instead of making an interface, you let the compile create one by taking a function directly instead of an interface in your datamanager, like this:
and then you just use it like how you want it! If I remember correctly, what the kotlin/jvm compiler do is the same as making an interface.
Hope it helps!
As @zsmb13 said, SAM conversions are only supported for Java interfaces.
You could create an extension function to make it work though:
Another solution would be by declaring a typealias, injecting it somewhere and invoking it. Here the example:
and then we inject that typealias to our class:
so we have our lambda:
Credits to my colleague Joel Pedraza, who showed me the trick while trying to find a solution <3.