Is it possible to use generics to deserialise / serialise any type of T that is annotated with @Serializable?
It is possible to make T of type Blah here and it will obviously work, but what type should T be to accept any input
Copy code
@Serializable
class Blah1()
inline fun <reified T : Blah1> blah(input: String){
Json.decodeFromString<T>(input)
}
Usecase: I want to do something like this and get rid of from / to json boilerplate
Copy code
fun <REQ, RES> doSomething(input: String, handler: REQ.() -> RES): String {
val req = Json.decodeFromString<REQ>(input)
val res = handler.invoke(req)
return Json.encodeToString<RES>(res)
}
REQ needs te be deserializable and RES should be serializable
janvladimirmostert
04/29/2023, 3:20 PM
this seems to compile
Copy code
inline fun <reified REQ : Serializable, reified RES : Serializable> doSomething(input: String, handler: REQ.() -> RES): String {
val req = Json.decodeFromString<REQ>(input)
val res = handler.invoke(req)
return Json.encodeToString<RES>(res)
}
let's see if it works ...
e
Emil Kantis
04/29/2023, 3:38 PM
I think you need to use reflection to get the KType of
reified T
and then there’s a
serializerFor(type :KType)
or something like it
Emil Kantis
04/29/2023, 3:39 PM
You can’t enforce
Serializable
as type constraint afaik, since it’s an annotation
j
janvladimirmostert
04/29/2023, 3:51 PM
it seems as long as you inline and reify everything, the compiler is happy and everything works
it didn't used to work in the past
this is the working solution
Copy code
inline fun <reified REQ, reified RES> doSomething(input: String, crossinline handler: (REQ) -> RES): String {
val req = Json.decodeFromString<REQ>(input)
val res = handler.invoke(req)
return Json.encodeToString<RES>(res)
}