Kotlin通用参数在函数中使用
我得到了这个问题的解决方案: 通配符在Kotlin通用的参数 ,但现在我有其他问题,仍然有关kotlin通用
我有一个抽象的类使用像下面的听api回调。 ApiRs是每个API响应对象从中inheritance的父对象
abstract class ApiCallback { open fun onSucceed(apiRsModel: T) {} open fun onFailed(code: Int, message: String) { } }
这次我写了一个函数来处理api成功与Retrofit2,比检查的东西和回调到UI,这里是我的function:
fun callbackWithSucceed(apiCallback: ApiCallback?, context: Context, response: Response?) { // unexpected error if (response == null) { encounterUnexpectedError(apiCallback, context, null) return } // check http val httpSucceed = response.code() == CODE_HTTP_SUCCEED && response.isSuccessful && response.body() != null if (!httpSucceed) { // HTTP response with error callbackWithFailed( apiCallback, response.code(), response.message()) return } apiCallback?.onSucceed(response.body()!!) } }
response
是Retrofit2类,其中包含我的API响应模型(body),每个响应模型都inheritance了ApiRs,我的目标是使用这种方式将模型传递给抽象类apiCallback?.onSucceed(response.body()!!)
会显示错误
types不匹配,需要T? 但是发现了ApiRs?
对不起,我有不好的通用概念。 我想函数open fun onSucceed(apiRsModel: T) {}
T应该inheritanceApiRs,因为我在类中定义,所以我不明白为什么显示错误信息?
您的response: Response
必须得到response: Response
,那么错误应该消失了。
传递给onSuccess
方法的T
的types必须与apiCallback
参数的通用types相匹配,该参数不是
而是
。