Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is lambda function not allowed here?

I've been working arround a GUI in Vaadin, with some given classes from my IT chief. It's all great and that, but, today, I have encountered that I cannot use a lambda expression in a addListener method type. This method is custom, as the 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 a lambda in addResetButtonClickedListener like this:

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

The compiler says that

  • Lambda expression's signature does not match the signature of the functional interface method resetButtonClicked()

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

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

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

like image 202
Shirkam Avatar asked Sep 29 '17 07:09

Shirkam


1 Answers

The functional interface consists of the method

public void resetButtonClicked()

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

rb.addResetButtonClickedListener(() -> {
    // handling code goes here
});
like image 56
daniu Avatar answered Sep 24 '22 08:09

daniu