Hey guys! I would like to make a mapper from a `Ht...
# ktor
s
Hey guys! I would like to make a mapper from a
HttpResponse
to a
Result<T>
But I can't get it to work?!
Copy code
class ResponseMapper {
    fun <T> map (httpResponse: HttpResponse) : Result<T> {
        return if (httpResponse.status.isSuccess()){
            Result.success(httpResponse.body()) // This is not allowed?
        } else if (httpResponse.status.value == 401) {
            Result.failure(exception = AuthException())
        } else {
            Result.failure(BackendException(errorCode = httpResponse.status.value))
        }
    }
}
Cannot use 'T' as reified type parameter. Use a class instead.
l
Can you make this method inline? You'll need it to be inline so it can get the type.
s
It want to be:
suspend inline fun <reified T> map
l
That looks right. The body method uses a reified T, and since your T is not reified, it can't use it.
s
I want to make map a
HttpResponse
that is returned from my
ktor.request
method:
Copy code
val response = ktor.request(PokemonApi.getAllPokemon(BATCH_SIZE, batch * BATCH_SIZE))
val entity = responseMapper.map(response)
but now
responseMapper.map(response)
is not allowed:
Not enough information to infer type variable T
l
It doesn't know what type 'entity' should be. Either specify a type on entity or use brackets in map and specify a type.
Copy code
val entity: Result<PokemonList> = ...
Or
Copy code
val entity = mapper.map<PokemonList>(response)
s
Is their a way that just does:
ResponseMapper.map(response)
?
l
How would it know what the type is? You can specify the type of entity as in my first example (replace the ... with your response mapper).
s
We normally use
Retrofit
and the
ResponseMapper
looked like this:
Copy code
fun <T> map(response: Response<T>): Result<T> = when {
    response.isSuccessful -> response.body()?.let(Result.Companion::success) ?: Result.failure(
        exception = Throwable("Http body is empty. HttpMessage: ${response.message()} HttpCode: ${response.code()}")
    )
    response.code() == 401 -> Result.failure(
        exception = AuthException()
    )
    else -> Result.failure(
        BackendException(
            errorCode = response.code()
        )
    )
}
l
That code gets the type from the retrofit Response<T>.
s
Is that possible to do with Ktor?
l
If you have a Response<T> in your old code, then T is known in the scope where you create the response. You'll want to just specify the type for your mapper instead.
Alternatively, if you're set on matching retrofit, I haven't used it, but ktorfit exists. It's supposed to be like retrofit, but using ktor, and thus cross-platform.