Kotlinx.serialization: ProtoBuf: Shall automatically generate ids when not-specified

Created on 23 Jan 2018  路  5Comments  路  Source: Kotlin/kotlinx.serialization

Test case:

Serializable class SampleMessage {
    var name: String? = null
}

fun main(args: Array<String>) {
    println(ProtoBuf.dumps(message))
}

Crashes with:

Exception in thread "main" java.util.NoSuchElementException: List is empty.
    at kotlin.collections.CollectionsKt___CollectionsKt.single(_Collections.kt:472)
    at kotlinx.serialization.protobuf.ProtoBuf$Companion.getProtoDesc(ProtoBuf.kt:390)
    at kotlinx.serialization.protobuf.ProtoBuf$Companion.access$getProtoDesc(ProtoBuf.kt:381)
    at kotlinx.serialization.protobuf.ProtoBuf$ProtobufWriter.getTag(ProtoBuf.kt:64)
    at kotlinx.serialization.protobuf.ProtoBuf$ProtobufWriter.getTag(ProtoBuf.kt:40)
    at kotlinx.serialization.TaggedOutput.writeElement(Tagged.kt:64)
    at kotlinx.serialization.KOutput.writeNullableSerializableElementValue(Serialization.kt:197)
    at SampleMessage.write$Self(TestOneOf.kt)
    at SampleMessage$$serializer.save(TestOneOf.kt)
    at SampleMessage$$serializer.save(TestOneOf.kt:5)
    at kotlinx.serialization.KOutput.write(Serialization.kt:99)
    at kotlinx.serialization.protobuf.ProtoBuf.dump(ProtoBuf.kt:415)
    at TestOneOfKt.main(TestOneOf.kt:17)

Expected behavior: ids are automatically assigned by ProtoBuf when they are not explicitly specified

feature protobuf

Most helpful comment

It should be a default behavior for the reasons of user-friendlines. If I write a serializable data class it should "just work" whether I'm trying to save it to JSON or Protobuf. Ensuring a stable Protobuf representation (with stable ids) is a secondary concern that only advanced Protobuf users shall worry about.

All 5 comments

Should it be default behaviour or should it be explicitly enabled in Protobuf object or perhaps @AutoId annotation on object in order to avoid caveats with auto-generated ids (reordering fields, etc)?

It should be a default behavior for the reasons of user-friendlines. If I write a serializable data class it should "just work" whether I'm trying to save it to JSON or Protobuf. Ensuring a stable Protobuf representation (with stable ids) is a secondary concern that only advanced Protobuf users shall worry about.

@sandwwraith, a question. Now I have following data class, how to make it work with ProtoBuf.dump()? thanks.

@Serializable
data class User(val id: Int, @Optional val nick: String = "")

@linux-china for now, you have to manually mark up class with @SerialId

@sandwwraith thanks. it works. I agree with @elizarov "It should be a default behavior for the reasons of user-friendlines. " especially for data class

Was this page helpful?
0 / 5 - 0 ratings