我用于 Retrofit 接口创建的通用函数出现编译器错误:推断类型是 Class<T>?但 Class<T!> 是预期的

use*_*225 2 generics android kotlin retrofit retrofit2

我在我的 Android (kotlin) 项目中使用 Retrofit。

我创建了我的界面:

interface StudentsInterface {
    @GET("foo/bar/{id}")
    suspend fun getStudent(@Path("id") myId: Int)
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个MyClient类,在其中定义了一个通用函数,用于从任何接口创建端点服务,如上面定义的代码:

class MyClient() {
    @Inject
    lateinit var  retrofit: Retrofit

    // this is my generic function
    fun <T> createService(interfaceClazz: Class<T>?): T {
        // Compiler error: Type mismatch: inferred type is Class<T>? but Class<T!> was expected
        return retrofit.create(interfaceClazz)
    }
}
Run Code Online (Sandbox Code Playgroud)

这样在另一堂课上我就可以:

val sService = myClient.createService(StudentsInterface::class.java)
...
Run Code Online (Sandbox Code Playgroud)

但是当我构建项目时,我总是收到编译器错误:Type mismatch: inferred type is Class<T>? but Class<T!> was expected在代码行中return retrofit.create(interfaceClazz)

为什么我会收到此错误?如何摆脱它?

Md.*_*man 5

Retrofit create 需要不可为 null 的参数。尝试使之interfaceClazz不可为空

fun <T> createService(interfaceClazz: Class<T>): T {
    // No error now
    return retrofit.create(interfaceClazz)
}
Run Code Online (Sandbox Code Playgroud)