Is it possible to use generics to deserialise / se...
# serialization
j
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
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
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
You can’t enforce
Serializable
as type constraint afaik, since it’s an annotation
j
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)
}
j
nice! then it's just good timing that I tried solving this again today after switching to 1.8.20