Passing a listener object as a function parameter to kotlin

I am trying to pass a listener from an action to a class (adapter).

In java (code from Action):

  private void setListeners() {
    adapterRecyclerView.setListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SomeCodehere....
                }
            });
}

(code from adapter)

public void setListener(View.OnClickListener listener) {
    this.listener = listener;
}

He works.

Now I'm trying to ferry Kotlin. First I translate the action (translate the action to kotlin):

    private fun setListeners() {
    // !! is not fine i know
    adapterRecyclerView!!.setListener  { v  ->
                          SomeCodehere....
    }
}

At this point, it still works. With adapter code still in java and class code in kotlin. Now translate the adapter to kotlin:

fun setListener(listener: View.OnClickListener) {
    this.listener = listener 
}

Now it will not work. The action does not compile.

Error: cannot deduce the type for this parameter "v". View.OnClickListener required. found (???) Unit.

How do I throw here? Why pass a parameter from kotlin to java work, and from kotlin to kotlin, is this not so?

+4
source share
2

Java SAM , Java. , Kotlin, ( , Kotlin lambdas ).

, : Android - Kotlin -

Kotin, SAM Lambda, . Java, . SAM Kotlin KT-7770.

, Kotlin, lambdas , , SAM. Lambdas. , .

, @joakim, , . :

object : View.OnClickListener {
    override fun onClick(v: View) {...}
})

, , . , , .

+6

adapterRecyclerView!!.setListener  { v  ->
                      SomeCodehere....
}

adapterRecyclerView!!.setListener(object : View.OnClickListener {

})

View.OnClickListener

+4

Source: https://habr.com/ru/post/1677942/


All Articles