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

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

问题描述

我创建了一个界面:

interface ProgressListener {
    fun transferred(bytesUploaded: Long)
}

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

but can use it only as an 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())})

但我收到错误:Type mismatch;必需 - ProgressListener, found - () ->单位?

我做错了什么?

推荐答案

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

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天全站免登陆