user842225
user842225

Reputation: 5979

My generic function for Retrofit interface creation get compiler error: inferred type is Class<T>? but Class<T!> was expected

I am using Retrofit in my Android (kotlin) project.

I created my interface:

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

I created a MyClient class in which I defined a generic function for creating endpoint service out from any interface like above code defined:

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)
    }
}

So that in another class I can :

val sService = myClient.createService(StudentsInterface::class.java)
...

But when I build the project, I always get compiler error: Type mismatch: inferred type is Class<T>? but Class<T!> was expected in the line of code return retrofit.create(interfaceClazz)

Why do I get this error? How to get rid of it?

Upvotes: 2

Views: 771

Answers (1)

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15423

Retrofit create needs non nullable arguments. Try to make interfaceClazz non nullable

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

Upvotes: 5

Related Questions