kluck
05/20/2019, 8:44 AM@Serializer(forClass = Option::class)
class OptionSerializer<T : Any>(private val dataSerializer: KSerializer<T>) : KSerializer<Option<T>> {
override val descriptor: SerialDescriptor = StringDescriptor.withName("OptionDescriptor")
override fun deserialize(input: Decoder): Option<T> {
return Option.fromNullable(input.decodeNullable(dataSerializer))
}
override fun serialize(output: Encoder, obj: Option<T>) {
when (obj) {
is None -> output.encodeNull()
is Some -> output.encodeNullable(dataSerializer, obj.t)
}
}
}
Then, I need to annotate my class @Serializable data class Stuff(@Serializable(with = OptionSerializer::class) val foo: Option<String>)
The downside is the verbosity, as the Option class is not annotated with @Serializable
, I have to add this chunk @Serializable(with = OptionSerializer::class)
to every optional property.
Here's a simple test and it's output: