Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why i can't use lambda for interface at kotlin? [duplicate]

Tags:

lambda

kotlin

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?

like image 594
user2699165 Avatar asked Oct 30 '22 07:10

user2699165


1 Answers

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.

like image 141
Christian Brüggemann Avatar answered Nov 07 '22 22:11

Christian Brüggemann