see, I have a Java class:
public final class JavaReceiveSingle {
public static void useSingle(Single single) {
single.doSth();
}
public static void useSingle2(SingleInterface singleInterface) {
singleInterface.doSth();
}
}
a Java interface:
public interface SingleInterface {
void doSth();
}
a kotlin interface:
interface Single {
fun doSth()
}
Now I can use lambda in a kotlin class like:
JavaReceiveSingle.useSingle2({})
But if I want to do the same thing to kotlin interface:
JavaReceiveSingle.useSingle({})
IDE will show error :Required: Single! Found: ()->Unit
And If I specify Single like:
JavaReceiveSingle.useSingle(Single{})
Still error:Interface Single does not have constructs!
Though the following code works:
JavaReceiveSingle.useSingle(object :Single{
override fun aa() {}
})
But why I can't use lambda for a kotlin interface?
Currently, SAM conversion is not supported for interfaces defined in Kotlin. There's an issue for that in YouTrack, but currently I'd recommend using functional types instead of single-method interfaces. If you want them to have a proper name, you may use type aliases, but don't overuse them. In many cases a functional type together with good method/variable names is expressive enough.
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