为什么我不能在kotlin上使用lambda作为接口? [英] why i can't use lambda for interface at kotlin?

查看:303
本文介绍了为什么我不能在kotlin上使用lambda作为接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看,我有一个Java类:

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();
    }
}

Java接口:

public interface SingleInterface {
    void doSth();
}

kotlin界面:

interface Single {
    fun doSth()
}

现在我可以在像这样的kotlin类中使用lambda了:

Now I can use lambda in a kotlin class like:

JavaReceiveSingle.useSingle2({})

但是如果我想对kotlin界面做同样的事情:

But if I want to do the same thing to kotlin interface:

JavaReceiveSingle.useSingle({})

IDE将显示错误:必需:单!找到:()->单位

IDE will show error :Required: Single! Found: ()->Unit

如果我将"Single"指定为:

And If I specify Single like:

JavaReceiveSingle.useSingle(Single{})

仍然错误:Interface Single没有构造!

Still error:Interface Single does not have constructs!

尽管以下代码有效:

JavaReceiveSingle.useSingle(object :Single{
    override fun aa() {}
})

但是为什么我不能在kotlin界面上使用lambda?

But why I can't use lambda for a kotlin interface?

推荐答案

当前, YouTrack 中存在一个问题,但目前我建议您改用函数类型单方法接口.如果您希望它们使用适当的名称,则可以使用类型别名,但不要过度使用它们.在许多情况下,功能类型与良好的方法/变量名称一起具有足够的表现力.

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.

这篇关于为什么我不能在kotlin上使用lambda作为接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆