https://kotlinlang.org logo
Title
s

sushma nayak

03/22/2021, 9:44 PM
Hi, I was trying to write a generic networking client using ktor.
override suspend fun <T : Any> getJsonFromRouter(router: APIRouter, success: Success<T>, failure: Failure) {
        try {
            val json = httpClient.get<String>(requestFromRouter(router))
            Json.decodeFromString(T.serializer(), json)
                .entries
                .also(success)
        } catch (ex: Exception) {
            Failure(error = ex)
        }
    }
I’m getting error on
T.serializer()
. Error = “Not enough information to infer type variable T”. On iOS we have Decodable which allows these kind of generic implementation. Was wondering if this is allowed on kotlin or this can’t be achieved and an actual type in place if generic T is required?
r

rnett

03/22/2021, 10:47 PM
If you can make
getJsonFromRouter
inline, you can use
reified
on
T
. Otherwise I'd probably take the serializer as a parameter or take the
KType
(but you lose type safety with
KType
).
s

sushma nayak

03/23/2021, 5:35 AM
Thanks!! Using the serializer as a parameter as I cant use inline
reified
 on 
T
because its defined in an interface.