Lambda expressions - can not set lambda parameter as argument to method
Solution 1
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
Solution 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();
}
Related videos on Youtube
Comments
-
Yura Buyaroff about 2 years
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.-
Shloim over 8 yearsAndroid compiles with Java 6. No lambdas in Java 6.
-
Yura Buyaroff over 8 yearsI know, I use retrolambda and other lambda expressions work
-
Shloim over 8 yearsYou should mention that in your question.
-
Bruno_Ferreira over 8 yearsIf you want to use lambda expressions on android: zserge.com/blog/android-lambda.html
-
-
Sleiman Jneidi over 8 yearsYou don't need the @FunctionalInterface annotation
-
k0ner over 8 yearsHave I written that you need? I just mentioned that to mark interface as functional and avoid errors in future