我在我的 Android (kotlin) 项目中使用 Retrofit。
我创建了我的界面:
interface StudentsInterface {
@GET("foo/bar/{id}")
suspend fun getStudent(@Path("id") myId: Int)
}
我创建了一个 MyClient
我在其中定义了一个通用函数,用于从任何接口(interface)创建端点服务,如上面定义的代码:
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)
}
}
这样在另一个类上我就可以:
val sService = myClient.createService(StudentsInterface::class.java)
...
但是当我构建项目时,我总是收到编译器错误:Type mismatch: inferred type is Class<T>? but Class<T!> was expected
在代码行return retrofit.create(interfaceClazz)
中
为什么我会收到此错误?如何摆脱它?
最佳答案
改造创建需要不可为空的参数。尝试使 interfaceClazz
不可为 null
fun <T> createService(interfaceClazz: Class<T>): T {
// No error now
return retrofit.create(interfaceClazz)
}
关于android - 我用于 Retrofit 接口(interface)创建的通用函数出现编译器错误 : inferred type is Class<T>?,但需要 Class<T!>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522202/