将java类文件转换为kotlin会导致编译错误
我有一个运行良好的java类文件,但如果我将其转换为Kotlin,就会出现一些问题。这是一个Java版本
public class CallbackWrapper<T> implements Callback<T> {
private Wrapper<T> wrapper;
public CallbackWrapper(Wrapper<T> wrapper) {
this.wrapper = wrapper;
}
public void onFailure(Call<T> call, Throwable t) {
wrapper.onResult(t, null);
}
public void onResponse(Call<T> call, Response<T> response) {
wrapper.onResult(null, response);
}
public interface Wrapper<T> {
void onResult(@Nullable Throwable t, @Nullable Response<T> response);
}
}
这就是我如何毫无问题地使用这个类
request.enqueue(CallbackWrapper<RegisterResponse> { throwable, response ->
response?.let { callBack.onResponse(response.body() ?: RegisterResponse()) }
throwable?.let { callBack.onFailed(throwable.message!!) }
})
这是转换后的Kotlin版本
class CallbackWrapper<T>(private val wrapper: CallbackWrapper.Wrapper<T>) : Callback<T> {
override fun onFailure(call: Call<T>, t: Throwable) {
wrapper.onResult(t, null)
}
override fun onResponse(call: Call<T>, response: Response<T>) {
wrapper.onResult(null, response)
}
interface Wrapper<T> {
fun onResult(t: Throwable?, response: Response<T>?)
}
}
问题是,在将其转换为Kotlin之后,我使用该类的代码块无法工作。我不明白他们之间有什么区别
下面是编译错误日志
Error:(17, 63) Type mismatch: inferred type is (???, ???) -> [ERROR :<ERROR FUNCTION RETURN TYPE>] but CallbackWrapper.Wrapper<RegisterResponse> 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.
# 1 楼答案
据我所知,您的代码有两个问题
首先,Kotlin不允许使用lambda实现Kotlin函数接口,因此您的lambda无法工作(它允许实现Java函数接口,因为Java没有适当的函数类型)。因此,要调用未更改的代码,您需要使用对象表示法:
如果您喜欢使用lambda,则可以以不同的方式声明
CallbackWrapper
类:这就是
but CallbackWrapper.Wrapper<RegisterResponse> was expected
部分但是,这仍然不起作用,这就引出了错误消息的前半部分是
inferred type is (???, ???) -> [ERROR :<ERROR FUNCTION RETURN TYPE>]
的原因。这基本上是类型推断失败。对callBack
的调用似乎与CallbackWrapper隐含的CallBack
接口不太匹配,我认为这可能与此有关编辑:
用更简洁的解决方案为您的改装问题添加了答案