Why is lambda function not allowed here?

I am working on a graphical interface in Vaadin, with some given classes from my CIO. All this is great, but today I came across the fact that I can not use the lambda expression in the addListener method addListener . This method is as common as an object that uses it. Here is the implementation:

 public class ResetButtonForTextField extends AbstractExtension { private final List<ResetButtonClickListener> listeners = new ArrayList<ResetButtonClickListener>(); private void addResetButtonClickedListener (ResetButtonClickListener listener) { listeners.add(listener); } //Some other methods and the call of the listeners } public interface ResetButtonClickListener extends Serializable { public void resetButtonClicked(); } 

To use this extension, you must do this:

 ResetButtonForTextField rb=ResetButtonForTextField.extend(button); rb.addResetButtonClickedListener(new ResetButtonClickListener() { @Override public void resetButtonClicked() { //Do some stuff here } }); 

If I use lambda in addResetButtonClickedListener as follows:

 rb.addResetButtonClickedListener(ev -> { //Do some magic here } 

The compiler says that

  • Lambda expression signature does not match resetButtonClicked () function interface method signature

  • The addResetButtonClickedListener (ResetButtonClickListener) method in the ResetButtonForTextField type is not applicable for arguments ((ev) → {})

Even if I define the lambda expression as follows: (ResetButtonClickListener ev) -> {} still gives an error.

So the question is, why can't I use a lambda expression there? Am I missing something in the code declaration?

+5
source share
2 answers

The functional interface consists of a method

 public void resetButtonClicked() 

without parameters. Your lambda is trying to implement it with a parameter of type ResetButtonClickListener. What you want to do is

 rb.addResetButtonClickedListener(() -> { // handling code goes here }); 
+11
source

The cause of the error is obvious in msg

The addResetButtonClickedListener (ResetButtonClickListener) method in the ResetButtonForTextField type is not applicable for arguments ((ev) → {})

therefore, you cannot use lambda when referring to the ev object, because the resetButtonClicked method of the resetButtonClicked interface ResetButtonClickListener not accept any parameters ...

do:

 ResetButtonForTextField r = .... r.addResetButtonClickedListener(() -> { //TODO }); 
+3
source

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


All Articles