Why is lambda function not allowed here?
Asked Answered
C

2

5

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?

Cassis answered 29/9, 2017 at 7:30 Comment(0)
I
11

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
});
Iloilo answered 29/9, 2017 at 7:34 Comment(1)
Oh, I got acostummed to ButtonClickListeners of Button class, that take one event argument. I didn't think about that. Thank you!Cassis
D
3

The reason of the error is clear in the msg

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

so you can not use the lambda referring to a object ev because the method resetButtonClicked of the interface ResetButtonClickListener doesn't take any parameter...

do :

ResetButtonForTextField r = ....
r.addResetButtonClickedListener(() -> {
     //TODO
});
Dethrone answered 29/9, 2017 at 7:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.