Is it possible to provide the framework with a DoubleArray serializer that would be used whenever a DoubleArray is encountered in any Serializable class?
DoubleArray and the like are not serializable yet.
From https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/custom_serializers.md it is clear that I could make a serializer for Foo:
@Serializable
class Foo {
val bar: DoubleArray = DoubleArray(3)
}
However, I would like to just make one serializer for DoubleArray because it is used in many large classes.
If this is not possible I will convert them to ArrayList
Hello,
You could do something like this:
@Serializable
class Foo(
@Serializable(DoubleArraySerializer::class) val bar: DoubleArray
)
object DoubleArraySerializer : KSerializer<DoubleArray> {
override val descriptor = ArrayListClassDesc(DoubleDescriptor)
override fun serialize(encoder: Encoder, obj: DoubleArray) {
encoder.encodeSerializableValue(ArrayListSerializer(DoubleSerializer), obj.asList())
}
override fun deserialize(decoder: Decoder): DoubleArray {
val doubles = decoder.decodeSerializableValue(ArrayListSerializer(DoubleSerializer))
return DoubleArray(doubles.size).apply {
doubles.forEachIndexed { index, double -> this[index] = double }
}
}
}
Thanks @q-litzler That's close to perfect.
Most helpful comment
Hello,
You could do something like this: