[英]Call Higher Order function of Kotlin from Java
Kotin Class科廷 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 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) requestData.setRetrofitCall(用户名 ->LoginService::changePassword)
Why Higher order function :为什么高阶 function :
Since i have to differentiate between each API call for calling a function from its feature hence trying to use.由于我必须区分每个 API 调用 function 的功能,因此尝试使用。
How to call the above highlighted code?如何调用上面高亮的代码?
Using Kotlin Functional Interfaces in Java is a little tricky and not very clean.在 Java 中使用 Kotlin 函数式接口有点棘手,而且不是很干净。
Your setRetrofitCall()
would need to look something like this:你的setRetrofitCall()
需要看起来像这样:
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;
}
}
);
More short code with Lamda expression带有 Lamda 表达式的更短代码
setRetrofitCall(s -> {
LoginService.getLoginData(s);
return Unit.INSTANCE;
});
If you want to use a named class and don't want to refer to Kotlin's interfaces, you can use ::
.如果你想使用命名为 class 并且不想引用 Kotlin 的接口,你可以使用::
。
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.否则,对于匿名 class,您可以根据 chakrapani 的回答使用 lambda 表达式。
setRetrofitCall(s -> {
LoginService.getLoginData(s);
return Unit.INSTANCE;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.