I don't understand the argument passing of the lambda expression in the listener

Viewed 485

It wasn't long after I started studying Kotlin.

There are parts that I don't understand about the delivery of lambda expressions in the Android listener.

In JAVA

botton.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
                
     }
});

i understand this code.

I understand this code. An anonymous object is created and passed as a parameter of setOnClickListener.

In Kotlin

button.setOnClickListener(object: View.OnClickListener {
       override fun onClick(p0: View?) {
           TODO("Not yet implemented")
       }
})

And I understand this code too. I understand it as it is a way to create anonymous objects similar to Java.

But

In Lamda of Kotlin

button?.setOnClickListener { }

I don't understand how this code works.

The lambda expressed here should be passed as an argument of setOnClickListener.

onClick() is an implementation function of the OnClickListener interface, how is it possible to be passed to setOnClickListener?

I don't understand well.

Isn't setOnClickListener an OnClickListener interface object that should be passed?

1 Answers

The lambda IS being passed as an argument to setOnClickListener!

You can test this by trying button?.setOnClickListener({ }) and noticing it still compiles.

Android Studio then suggests changing it to button?.setOnClickListener(){ }, as Kotlin's coding convention dictates:

If a call takes a single lambda, pass it outside of parentheses whenever possible.

This gives us button?.setOnClickListener(){ }.

The () is marked as redundant, due to "Remove unnecessary parentheses from function call with lambda" leading to... button?.setOnClickListener { }!

Note: You can ctrl / cmd click the function name and the signature shows public void setOnClickListener(@Nullable OnClickListener l)

Related