4

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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Yura Buyaroff
  • 1,718
  • 3
  • 18
  • 31

2 Answers2

5

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

k0ner
  • 1,086
  • 7
  • 20
2

Yes, correct answer is "You can use lambdas only with Functional interfaces. It means that your interface has to specify only one method."

For other who will search for some workaround this is my solution: Devide interface on two functional interfaces

public interface SuccessLoginUserInterface {
    void onLoginSuccess(LoginResponseEntity login);
}

public interface FailLoginUserInterface {
    void onLoginFail(ServerResponse sr);
}

And your lambda expression will look well:

private void makeLoginRequest(LoginRequestEntity loginRequestEntity) {
    new LoginUserService(loginRequestEntity)
            .setsListener(
                    login -> loginSuccess(login),
                    sr -> loginFail(sr))
            .execute();
}
Yura Buyaroff
  • 1,718
  • 3
  • 18
  • 31