Skip to content

Encoding value classes fails in Protocol Buffers #3045

@ScottPeterJohnson

Description

@ScottPeterJohnson

Describe the bug
Attempting to encode value classes with default generated serializers fails using Protocol Buffers.

To Reproduce

fun main(){
    ProtoBuf {}.encodeToByteArray(Example(1))
}
@Serializable
@JvmInline
value class Example(val raw : Int)

Expected behavior
Encodes correctly as the base type like e.g. json does.
Currently gives:
Exception in thread "main" kotlinx.serialization.SerializationException: No tag in stack for requested element
at kotlinx.serialization.protobuf.internal.ProtobufTaggedBase.popTag(ProtobufTaggedBase.kt:55)
at kotlinx.serialization.protobuf.internal.ProtobufTaggedEncoder.encodeInline(ProtobufTaggedEncoder.kt:178)

Possibly related:
#1774

Workaround:
Write a custom serializer:

fun main(){
    ProtoBuf {}.encodeToByteArray(Example(1))
}

@JvmInline
@Serializable(with = ExampleSerializer::class)
value class Example(val raw : Int)
object ExampleSerializer : KSerializer<Example> {
    override val descriptor: SerialDescriptor
        get() = Int.serializer().descriptor
    override fun serialize(
        encoder: Encoder,
        value: Example
    ) {
        encoder.encodeInt(value.raw)
    }

    override fun deserialize(decoder: Decoder): Example {
        return Example(decoder.decodeInt())
    }
}

Environment

  • Kotlin version: 2.2.0
  • Library version: 1.9.0
  • Kotlin platforms: JVM
  • Gradle version: 8

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions