Passing lambda instead of interface

前端 未结 5 1818
执念已碎
执念已碎 2020-12-08 12:44

I have created an interface:

interface ProgressListener {
    fun transferred(bytesUploaded: Long)
}

but can use it only as an anonymous clas

5条回答
  •  余生分开走
    2020-12-08 13:26

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

    Edit:

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

提交回复
热议问题