Lambda Expressions – You cannot set a lambda parameter as an argument to a method
I’m trying to use lambda expressions on Android using retrolambda. In the following code, I need to add a listener as an interface:
public interface LoginUserInterface {
void onLoginSuccess(LoginResponseEntity login);
void onLoginFail(ServerResponse sr);
}
Code
private void makeLoginRequest(LoginRequestEntity loginRequestEntity) {
new LoginUserService(loginRequestEntity)
.setListener(
login -> loginSuccess(login),
sr -> loginFail(sr))
.execute();
}
private void loginSuccess(LoginResponseEntity login) {
TODO loginSuccess
}
private void loginFail(ServerResponse sr) {
TODO loginFail
}
However, Android Studio marks the red loginSuccess(login) and loginFail(sr) as errors
and displays the messages “LoginResponseEntity cannot be applied to” and “ServerResponse cannot be applied to”
So I can’t set the lambda parameter “login” to the parameter of the method loginSuccess(login).
Please help me understand what’s wrong with this expression.
Solution
You can only combine lambda with >Functional interfaces together. This means that your interface must specify only one method.
The best way to keep this in mind (simply – to be able to use lambdas instead of anonymous classes) is to add @FunctionalInterface
annotations to your interface.
@FunctionalInterface
public interface LoginUserInterface {
LoginResult login(...)
}
The value of LoginResult
is then dispatched