我有一个运行良好的Java类文件,但是如果将其转换为Kotlin,则会出现一些问题.这是Java版本
public class CallbackWrapper implements Callback {
private Wrapper wrapper;
public CallbackWrapper(Wrapper wrapper) {
this.wrapper = wrapper;
}
public void onFailure(Call call, Throwable t) {
wrapper.onResult(t, null);
}
public void onResponse(Call call, Response response) {
wrapper.onResult(null, response);
}
public interface Wrapper {
void onResult(@Nullable Throwable t, @Nullable Response response);
}
}
这就是我毫无问题地使用此类的方式…
request.enqueue(CallbackWrapper { throwable, response ->
response?.let { callBack.onResponse(response.body() ?: RegisterResponse()) }
throwable?.let { callBack.onFailed(throwable.message!!) }
})
这是转换后的Kotlin版本
class CallbackWrapper(private val wrapper: CallbackWrapper.Wrapper) : Callback {
override fun onFailure(call: Call, t: Throwable) {
wrapper.onResult(t, null)
}
override fun onResponse(call: Call, response: Response) {
wrapper.onResult(null, response)
}
interface Wrapper {
fun onResult(t: Throwable?, response: Response?)
}
}
问题是将其转换为Kotlin后,我正在使用此类的代码块无法正常工作.我不明白它们之间有什么区别.
这是编译错误日志
Error:(17, 63) Type mismatch: inferred type is (???, ???) -> [ERROR :] but CallbackWrapper.Wrapper was expected
Error:(17, 65) Cannot infer a type for this parameter. Please specify it explicitly.
Error:(17, 76) Cannot infer a type for this parameter. Please specify it explicitly.
解决方法:
据我所知,您的代码有两个问题.
首先是Kotlin不允许使用lambda来实现Kotlin功能接口,因此您的lambda无法正常工作(它确实允许实现Java功能接口,因为Java没有适当的函数类型).因此,要使代码保持不变,您想使用对象符号来代替:
request.enqueue(CallbackWrapper(object : CallbackWrapper.Wrapper {
override fun onResult(throwable: Throwable?, response: Response?) {
response?.let { callBack.onResponse(response.body() ?: RegisterResponse()) }
throwable?.let { callBack.onFailure(throwable.message!!) }
}
}))
如果您更喜欢使用lambda,则可以不同地声明CallbackWrapper类:
typealias Wrapper = (t: Throwable?, response: Response?) -> Unit
class OtherCallbackWrapper(val wrapper: Wrapper) : Callback {
override fun onFailure(call: Call, t: Throwable) = wrapper.invoke(t, null)
override fun onResponse(call: Call, response: Response) = wrapper.invoke(null, response)
}
这就是CallbackWrapper.Wrapper< RegisterResponse>被期望
部分照顾.
但是,这仍然行不通,这使我们推断出错误消息的前半部被推断为type((???,???)-> [错误:].这基本上是类型推断失败的原因.对CallBack的调用似乎与CallbackWrapper所暗示的CallBack接口不太匹配,我希望这可能与它有关.
编辑:
为您的改造问题添加了答案,并提供了更简洁的解决方案.
标签:kotlin,java
来源: https://codeday.me/bug/20191111/2020412.html