kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Decode element method always called for optional element when decodeSequentially is used

Open rnett opened this issue 3 months ago • 2 comments

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

rnett avatar Sep 15 '25 21:09 rnett

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.

sandwwraith avatar Sep 16 '25 10:09 sandwwraith

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.

rnett avatar Sep 16 '25 17:09 rnett