How to return generic object as return type

Hi ,

i have an interface with get ,post like below

interface IHttpClient {
suspend fun post(
body: Any, urlEndPoint: String
): Response
suspend fun get(urlEndPoint: String): Response
}

which will implemented by volley or retrofit with help of DI, but currently here my response object is of type(retrofit2.Response) , but i want make this generic so that it will support any HTTP Client (volley etc…)

but not sure exactly how to achieve this

Quite simply: :wink:

interface HttpClient<out RESPONSE> {
	suspend fun get(urlEndPoint: String): RESPONSE
	suspend fun post(body: Any, urlEndPoint: String): RESPONSE
}

and then:

class RetrofitHttpClient : HttpClient<Response> {
	override suspend fun get(urlEndPoint: String): Response = ...
	override suspend fun post(body: Any, urlEndPoint: String): Response = ...
}

for below

suspend fun <C> get(urlEndPoint: String): RESPONSE<C>

out RESPONSE<C> not working

If you also add C type which would be a separate generic type so it’s oblivious that it wouldn’t work. I was only typing that example by hand :slight_smile:

so is there any way i can return RESPONSE<C> as generic

It would then make more sense to just return the C directly instead of trying something like RESPONSE<C>. The only other way is to wrap responses in your own type, like: interface Response<T>. It depends on what you would like to do.