How can I support default values in my addon-forma...
# serialization
f
How can I support default values in my addon-format? How can I 'tell' the deserializer "here, this value doesn't exist, use the default value instead"
s
It would be picked up automatically if you didn't provide it
f
How can I "not provide it"? I need to return a value to
decodeX
after all
My decoder is a
NamedValueDecoder
if that matters
s
Roughly speaking, deserialization of each property performed in 2 steps: first, deserializer calls
decodeElementIndex
which is used to determine current property in stream. Then, deserializer uses this index to call correctly typed
decodeX
function. Therefore, if you return from
decodeElementIndex
indices, say, 1 and 3, deserializer would be able to infer that the property 2 is missing and use its default value
f
I think I understand. Thank you!
I have a decoder that basically decodes into a
Map<String, Primitive>
. When decoding primitives implementing
decodeElementIndex
is simple enough because I can just do something like this:
Copy code
override fun decodeElementIndex(desc: SerialDescriptor): Int {
            while (position < desc.elementsCount) {
                val name = desc.getTag(position++)
                if (name in map.keys) {
                    return position - 1
                }
            }
            return CompositeDecoder.READ_DONE
}
This doesn't work for non-primitives. The problem is that structures like lists and nested objects encode using some fairly arbitrary format, like instead of having in a primitive
"MyPrimitive" -> 1
They encode like this
Copy code
"MyList.size" -> 2
"MyList.1" -> 10
"MyList.2" -> 5
So, I could handle this case manually, check for size etc, but I'm thinking it's not practical to do for every serializer that might serialize like this. Is there some helper I can use for this? Perhaps an example implementation?
s
List indices are mapped almost one-to-one on elements indices
If I understood your question right, you can take a look at
TreeJsonInput.kt
It is a
NamedValueDecoder
which switches between different implementation if currents structure either a map, a list, or an object