I wrote two different listeners for my button:
myButton.setOnClickListener{myOnClick()}
myButton.setOnKeyListener{myOnKeyListener()}
The first one is OK for the compiler. But second one gives an error. It says Expected 3 parameters of types View!, Int, KeyEvent!
Considering that these are the listeners in the View class:
public interface OnClickListener {
void onClick(View v);
}
public interface OnKeyListener {
boolean onKey(View v, int keyCode, KeyEvent event);
}
Any idea about why is asking me for the parameters in one situation but not in the other?
It's because of OnClickListener.onClick
takes only one parameter but OnKeyListener.onKey
takes three. In Kotlin you don't need to specify single lambda's parameter and you can access it with the implicit name it
. But when lambda expects more parameters you cannot access them with it
anymore. That's why you have to explicitly give them names.