且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

传递 lambda 而不是接口

更新时间:2023-10-05 14:53:40

正如@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)
}