My generic function for Retrofit interface creation get compiler error: inferred type is Class<T>? but Class<T!> was expected
My generic function for Retrofit interface creation get compiler error: inferred type is Class<T>? but Class<T!> was expected
我在我的 Android (kotlin) 项目中使用 Retrofit。
我创建了我的界面:
interface StudentsInterface {
@GET("foo/bar/{id}")
suspend fun getStudent(@Path("id") myId: Int)
}
我创建了一个 MyClient
class,我在其中定义了一个通用函数,用于从上面代码定义的任何接口创建端点服务:
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)
}
}
所以在另一个class我可以:
val sService = myClient.createService(StudentsInterface::class.java)
...
但是当我构建项目时,我总是在代码行return retrofit.create(interfaceClazz)
中得到编译器错误:Type mismatch: inferred type is Class<T>? but Class<T!> was expected
为什么会出现此错误?如何摆脱它?
Retrofit 创建需要不可为 null 的参数。尝试使 interfaceClazz
不可为空
fun <T> createService(interfaceClazz: Class<T>): T {
// No error now
return retrofit.create(interfaceClazz)
}
我在我的 Android (kotlin) 项目中使用 Retrofit。
我创建了我的界面:
interface StudentsInterface {
@GET("foo/bar/{id}")
suspend fun getStudent(@Path("id") myId: Int)
}
我创建了一个 MyClient
class,我在其中定义了一个通用函数,用于从上面代码定义的任何接口创建端点服务:
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)
}
}
所以在另一个class我可以:
val sService = myClient.createService(StudentsInterface::class.java)
...
但是当我构建项目时,我总是在代码行return retrofit.create(interfaceClazz)
Type mismatch: inferred type is Class<T>? but Class<T!> was expected
为什么会出现此错误?如何摆脱它?
Retrofit 创建需要不可为 null 的参数。尝试使 interfaceClazz
不可为空
fun <T> createService(interfaceClazz: Class<T>): T {
// No error now
return retrofit.create(interfaceClazz)
}