传递lambda而不是接口 [英] Passing lambda instead of interface

查看:83
本文介绍了传递lambda而不是接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个界面:

I have created an interface:

interface ProgressListener {
    fun transferred(bytesUploaded: Long)
}

但只能将其用作匿名类,不能用作lambda

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

我认为应该用lambda代替它:

I think it should be a possibility to replace it by lambda:

dataManager.createAndSubmitSendIt(title, message, {System.out.println(it.toString())})

但是我遇到错误:类型不匹配;必需-ProgressListener,找到-()->单位?

But I am getting error: Type mismatch; required - ProgressListener, found - () -> Unit?

我在做什么错了?

推荐答案

正如@ zsmb13所说,仅Java接口支持SAM转换.

As @zsmb13 said, SAM conversions are only supported for Java interfaces.

您可以创建一个扩展功能以使其正常运行:

You could create an extension function to make it work though:

// Assuming the type of dataManager is DataManager.
fun DataManager.createAndSubmitSendIt(title: String, 
                                      message: String, 
                                      progressListener: (Long) -> Unit) {
    createAndSubmitSendIt(title, message,
        object : ProgressListener {
            override fun transferred(bytesUploaded: Long) {
                progressListener(bytesUploaded)
            }
        })
}

Kotlin 1.4将带来功能接口,该功能接口可为Kotlin中定义的接口启用SAM转换.这意味着,如果使用fun关键字定义接口,则可以使用lambda调用函数.像这样:

Kotlin 1.4 will bring function interfaces that enables SAM conversions for interfaces defined in Kotlin. This means that you can call your function with a lambda if you define your interface with the fun keyword. Like this:

fun interface ProgressListener {
    fun transferred(bytesUploaded: Long)
}

这篇关于传递lambda而不是接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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