Using lambdas does not compile when trying to pass in a method expecting a SAM interface

前端 未结 2 1425
旧时难觅i
旧时难觅i 2021-01-26 04:03

I am trying to understand lambdas and Kotlin. I created this trivial example

interface OnClickListener {
    fun onClick(s: String)
}

class Button {
    var cli         


        
2条回答
  •  不知归路
    2021-01-26 04:56

    As Taseer Ahmad points out, SAM conversion only works for Java interfaces since Kotlin already has proper function types. Of course, an easy way around this is to simply define a second setOnClickListener method that takes a function type

    class Button {
        var clickListener: OnClickListener? = null
    
        fun setOnClickListener(listener: OnClickListener?) {
            clickListener = listener
        }
    
        inline fun setOnClickListener(crossinline listener: (String) -> Unit) {
            setOnClickListener(object : OnClickListener { 
                override fun onClick(s: String) = listener(s)
            })
        }
    
        fun click() {
            clickListener?.onClick("hello")
        }
    }
    

    This then allows you to write b.setOnClickListener { println(it) }. I always inline methods like this as a habit, but it's not really required, so you can remove the inline and crossinline if you want.

提交回复
热议问题