Call Higher Order function of Kotlin from Java

3k Views Asked by At

Kotin Class

class LoginService{

    fun getLoginData(loginData: String) {
        request(LoginApi.create().getLoginData(loginData))}
    }

    fun changePassword(_:String){
        request(LoginApi.create().changePassword(_)
    }

    class RequestData {
        var retrofitCall: ((String) -> Unit)? = null
    }
}

Java Class

class LoginModel{

    private void loginData(){
        RequestData data = new RequestData();
        requestData.setRetrofitCall(username ->LoginService::getLoginData)
    }

    private void changePassword(){
        RequestData data = new RequestData();
        requestData.setRetrofitCall(username ->LoginService::changePassword)
     }
 }

requestData.setRetrofitCall(username ->LoginService::changePassword)

Why Higher order function :

Since i have to differentiate between each API call for calling a function from its feature hence trying to use.

How to call the above highlighted code?

3

There are 3 best solutions below

1
TheWanderer On BEST ANSWER

Using Kotlin Functional Interfaces in Java is a little tricky and not very clean.

Your setRetrofitCall() would need to look something like this:

setRetrofitCall(new Function1<String, Unit>() {
        @Override
        public Unit invoke(String s) {
            LoginService.getLoginData(s); //I'm pretty sure LoginService is supposed to be static?
            return Unit.INSTANCE;
        }
    }
);
0
chakrapani On

More short code with Lamda expression

setRetrofitCall(s -> {
        LoginService.getLoginData(s); 
            return Unit.INSTANCE;
    });
0
Oded Niv On

If you want to use a named class and don't want to refer to Kotlin's interfaces, you can use ::.

class CallbackHandler {
  Unit invoke(String s) {
    LoginService.getLoginData(s);
    return Unit.INSTANCE;
  }
}

CallbackHandler handler = new CallbackHandler();
setRetrofitCall(handler::invoke);

Otherwise for anonymous class you can use lambda expression per chakrapani's answer.

setRetrofitCall(s -> {
  LoginService.getLoginData(s); 
  return Unit.INSTANCE;
});