Mihai Voicescu
10/22/2021, 4:14 PMabstract class Demo<RequestT> {
@PublishedApi
internal inline fun <reified T : RequestT> requestToJSON(payload: T): String {
return Json.encodeToString(payload)
}
suspend inline fun <reified Res : RequestT> request(payload: Res): String {
return req(requestToJSON(payload))
}
abstract suspend fun req(payload: String): String
}
Joffrey
10/22/2021, 7:34 PMreified
because you want to call a reified
method yourself (like in the present case, where you are trying to call encodeToString
), then it simply means you'll need to give up on the sugar for the call of that method and use the non-reified version (there is probably one in general).
In this specific case, the non-reified version of Json.encodeToString()
needs a Serializer
, so you could just define your non-reified public method by asking for the same thing, and then make your reified version by calling this one and using the same trick as encodeToString()
to get the extra information you need:
private fun <T : RequestT> requestToJSON(payload: T, serializer: Serializer<T>): String {
return Json.encodeToString(serializer, payload)
}
suspend fun <Res : RequestT> request(payload: Res, serializer: Serializer<T>): String {
return req(requestToJSON(payload))
}
suspend inline fun <reified Res : RequestT> request(payload: Res): String {
return request(payload, Json.serializersModule.serializer<Res>())
}