Paulius Ruminas
06/08/2019, 8:12 PM@Serializable
sealed class Foo<T : Any> {
@Serializable
data class Bar<T : Any>(val o: T) : Foo<T>()
@Serializable
data class Baz(val o: String) : Foo<String>()
}
It's not possible to do something like PolymorphicSerializer(Foo::class, UnitSerializer)
.sandwwraith
06/09/2019, 9:46 AMBarSerializer(PolymorphicSerializer(Any::class))
Paulius Ruminas
06/09/2019, 1:54 PM@Serializable
sealed class Result<T : Any> {
@Serializable
data class Success<T : Any>(val result: T) : Result<T>()
@Serializable
data class Failure<T : Any>(val error: String) : Result<T>()
}
private inline fun <reified T : Any, reified R : Any> run(data: T): Result<R> {
val messageSerializer = T::class.serializer()
val json = jsonSerializer.stringify(messageSerializer, data)
// Send message...
// Receive response...
val response: String // can either be Result.Success<R> or Result.Failure<R>
// Create both serializers for success and failure
val successSerializer = Result.Success.serializer(R::class.serializer())
val failureSerializer = Result.Failure.serializer(R::class.serializer())
// How to register both these serializers at runtime for Result<R> class?
val polymorphicSerializer = PolymorphicSerializer(Result::class)
return jsonSerializer.parse(polymorphicSerializer, response)
}
private val jsonSerializer by lazy {
Json(
configuration = JsonConfiguration.Stable,
context = SerializersModule {}
)
}
Paulius Ruminas
06/10/2019, 10:19 AMJson
at runtime with different generic types each time run is called. But I don't know if this is the most effective way to do this.
val jsonSerializer = Json(
configuration = JsonConfiguration.Stable,
context = SerializersModule {
include(JsonSerializer.context)
polymorphic<RpcResponse<R>> {
addSubclass(RpcResponse.Success.serializer(R::class.serializer()))
addSubclass(RpcResponse.Failure.serializer(R::class.serializer()))
}
}
)
Paulius Ruminas
06/10/2019, 4:16 PMsandwwraith
06/10/2019, 4:34 PMPaulius Ruminas
06/10/2019, 6:08 PMSo you don't really know what `T`s you will have and they can be literally any class?Yes that's the case. I can't really register them ahead of time.