Decode element method always called for optional element when decodeSequentially is used
Describe the bug
I'm not sure if this is actually a bug or I'm misunderstanding the behavior somehow. The details are here.
To Reproduce
I have a class like this:
@Serializable
data class Foo(val bar: String = "baz")
I'm using it with a custom deserializer that enables sequential decoding. I see decodeStringElement being called for bar which gives me no possibility of handling the missing state of the optional value, i.e. signaling to use the default.
Expected behavior
There is some way to flag that an element is not present and the default should be used.
Environment
- Kotlin version: 2.2.0
- Library version: 1.9.0
- Kotlin platforms: JVM
- Gradle version: 9.0.0
Since decodeSequentially skips calls to decodeElementIndex by design (https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization.encoding/-composite-decoder/decode-sequentially.html), it indeed cannot handle missing/optional data. Generally, it is your responsibility to decide whether input can be sequentially decoded or not, so if there's some property missing and you cannot substitute it with some format defaults (e.g., 0 for Ints), then decodeSequentially likely should return false.
Ah I see, so that decision should be based off of the descriptor the composite decoder was created with? It would be helpful to node this in the KDoc.