首页 文章

Kotlin泛函参数在函数中使用

提问于
浏览
1

我得到了这个问题的解决方案:Wildcards generic in Kotlin for parameter,但现在我有其他问题仍然与kotlin generic有关

我有一个抽象类用于listen api回调,如下所示 . ApiRs是每个API响应对象从其继承的父对象

abstract class ApiCallback<in T : ApiRs> {

    open fun onSucceed(apiRsModel: T) {}

    open fun onFailed(code: Int,
                      message: String) {
    }
}

这次我写了一个函数来处理api成功使用Retrofit2,而不是检查一下并回调到UI,这是我的函数:

fun <T : ApiRs> callbackWithSucceed(apiCallback: ApiCallback<T>?,
                                        context: Context,
                                        response: Response<out ApiRs>?) {
        // 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响应模型(正文),每个响应模型都继承了ApiRs,我的目标是使用这种方式将模型传递给抽象类 apiCallback?.onSucceed(response.body()!!) 但它会显示错误

类型不匹配,需要T?但是找到了ApiRs?

抱歉,我对通用概念不好 . 我认为函数 open fun onSucceed(apiRsModel: T) {} T应该继承ApiRs,因为我在类中定义,所以我无法理解为什么显示错误信息?

1 回答

  • 1

    你的 response: Response<out ApiRs>? 必须是 response: Response<out T>? ,那么错误就应该消失了 .

    将传递给方法 onSuccessT 的类型必须与 apiCallback 参数的泛型类型匹配,该参数不是 <ApiRs> 而是 <T> .

相关问题