Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 246
Yura Buyaroff Avatar asked Oct 17 '25 05:10

Yura Buyaroff


2 Answers

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

like image 86
k0ner Avatar answered Oct 19 '25 21:10

k0ner


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();
}
like image 40
Yura Buyaroff Avatar answered Oct 19 '25 21:10

Yura Buyaroff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!