Kotlin中通用通配符作为参数 [英] Wildcards generic in Kotlin for parameter
问题描述
我有一个用于侦听api回调的抽象类,如下所示. ApiRs是每个API响应对象都继承自其的父对象
I have an abstract class using for listen api callback like below. ApiRs is a parent object that every API response object inherit from it
abstract class ApiCallback<in T : ApiRs> {
open fun onSucceed(apiRsModel: T) {}
open fun onFailed(code: Int,
message: String) {
}
}
我还写了一个函数,在请求api之前检查网络状态,如果网络未连接,它将触发onFailed
and i also write a function to check network status before request api, if network is not connected, then it will trigger onFailed
fun isNetworkAvailable(apiCallback: ApiCallback<ApiRs>?,
context: Context): Boolean{
val connectivityManager = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connectivityManager.activeNetworkInfo
// device network unreachable
if (networkInfo == null
|| !networkInfo.isConnected) {
// callback with network error
apiCallback?.onFailed(code, message)
return false
}
return true
}
参数类型ApiCallback<ApiRs>?
实际上我想像ApiCallback<? extends ApiRs>?
一样写,但是Kotlin没有通配符.如果我将通用替换为ApiCallback<out ApiRs>?
,它将显示错误
the parameter type ApiCallback<ApiRs>?
actually i want to write it like ApiCallback<? extends ApiRs>?
, but Kotlin has no wildcard. If i replace the generic to ApiCallback<out ApiRs>?
, it will show an error
投影与ApiCallback的相应类型参数的方差冲突
Projection is conflicting with variance of the corresponding type parameter of ApiCallback
有什么办法可以解决?还是我对Kotlin泛型的概念有误?
Is there any way to fix it? or just i have wrong concept of Kotlin generic?
2017/09/18更新-正确的方法是:
2017/09/18 update - The right way is :
方法:
fun <T : ApiRs> isNetworkAvailable(apiCallback: ApiCallback<T>?,
context: Context): Boolean {
val connectivityManager = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connectivityManager.activeNetworkInfo
// device network unreachable
if (networkInfo == null
|| !networkInfo.isConnected) {
// callback with network error
callbackWithFailed(
apiCallback,
ApiError.API_ERROR_CODE_0,
context.getString(R.string.api_error_code_0))
return false
}
return true
}
推荐答案
我了解您希望您的方法接受apiCallback: ApiCallback<ApiRs>?
的方式是ApiCallback
的通用类型可以是ApiRs
本身,也可以是以下任何一种它的子类型. Kotlin具有通配符,而不是通配符上限.您可以这样声明函数:
I understand that you want to accept apiCallback: ApiCallback<ApiRs>?
in your method in a way that the generic type of ApiCallback
can be ApiRs
itself or any of its subtypes. Instead of wildcards, Kotlin has upper bounds. You can declare the function like this:
fun <T: ApiRs> isNetworkAvailable(apiCallback: ApiCallback<T>?,
context: Context)
这篇关于Kotlin中通用通配符作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!