有一个基类a,B类和C类都从a扩展而来

in A it has function to create a retrofit service, which takes a class type as pram:

protected fun <T> createRemoteService(clazz: Class<T>, baseUrl: String): T {
    return Retrofit.Builder()
        .baseUrl(baseUrl)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create(createGson()))
        .build()
        .create(clazz)
}

and in class B and C, the service could be created as (with IBService::class.java or ICService::class.java passed in respectively):

in B:

var remoteServ: IBService
init {
    remoteApi = createRemoteService(IBService::class.java, getBaseUrl())
}

and in C:

var remoteServ: ICService
init {
    remoteApi = createRemoteService(ICService::class.java, getBaseUrl())
}

it is ok to pass IBService::class.java as the Class<T>

would like to have a abstract function in base A to return the class type

abstract fun<T> getRemoteServiceClassType() : Class<T>

so it could be done in base A to create the service by getting the class type

remoteServ: Any = createRemoteApi(getRemoteServiceClassType(), getBaseUrl())

并在B类中实现(获取错误):

override fun<T> getRemoteServiceClassType() : Class<T> {
    return IBService::class.java  //<=== got compiler error “Type inference 
                                  // failed. Expected type mismatch: required Class<T>
                                  // found Class<IBService>
}

interface IBService {
    @GET
    fun getRemoteData(@Url url: String,
                  @HeaderMap headers: Map<String, String>,
                  @QueryMap params: Map<String, String>?): 
        Call<BResponseData>

}

why cant return IBService::java.class for the Class<T>, but passing IBService::class.java to a function where requires a Class<T> is ok?

推荐答案

The "correct" signature for getRemoteServiceClassType is

abstract fun getRemoteServiceClassType() : Class<*>

如果有任何课程可以返回,或者

abstract fun getRemoteServiceClassType() : Class<out SuperType>

如果所有服务都应该有一个公共的超类型.有关说明,请参见https://kotlinlang.org/docs/reference/generics.html.

Kotlin相关问答推荐

用普通Kotlin理解Gradle的Kotlin DSL'""

在Mapstruct中重用@映射定义

何时使用figureEach

如何让Gradle8+在编译Kotlin代码之前编译Groovy代码?然后把它们混合在一个项目中?

如何避免使用公共类实现内部接口

如何进行基于lambda/谓词的两个列表的交集?

如何在操作系统版本上正确获取Room数据库的路径>;=26 sdk?

在 Kotlin 中将 Array 转换为 IntArray 时丢失值

Webpack 配置未应用于 kotlin 多平台react 项目

TzdbZoneRulesProvider 在 java.time 中不工作

使用 kotlin 流删除 map 中具有某些相似性的值

伴随对象在变量更改时更改它的值

Kotlin - 当表达式返回函数类型

为什么 IntelliJ Idea 无法识别我的 Spek 测试?

Kotlin 枚举中的循环引用

如何退出 Kotlinc 命令行编译器

无法在Kotlin中使用argb color int值?

重复构建失败To use Coroutine features, you must add `ktx`......

Kotlin-将UTC转换为当地时间

如何在 spring-boot Web 客户端中发送请求正文?