Lambda expressions - can not set lambda parameter as argument to method

Yura Buyaroff picture Yura Buyaroff · Nov 30, 2015 · Viewed 12k times · Source

I'm trying use lambda expressions on Android using retrolambda. In code below I need to add listener that is 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
    }

But Android Studio marks red loginSuccess(login) and loginFail(sr) as mistakes and shows message "LoginResponseEntity cannot be applied to " and "ServerResponse cannot be applied to "
So I can not set lambda parameter 'login' as argument to method loginSuccess(login).
Please help me to understand what's wrong with this expression.

Answer

k0ner picture k0ner · Nov 30, 2015

You can use lambdas only with Functional interfaces. It means that your interface has to specify only one method.

To remember about it (simply - to have the ability of using lambdas instead of anonymous classes), the best is to put @FunctionalInterface annotation to your interfaces.

@FunctionalInterface
public interface LoginUserInterface {
    LoginResult login(...)
}

and then dispatch on the value of LoginResult