avro-kotlin / avro4k

Avro format support for Kotlin
Apache License 2.0
188 stars 36 forks source link

Representing a union of a record and an enum #101

Closed keirlawson closed 2 years ago

keirlawson commented 3 years ago

I have a schema that includes the below type:

{
    "name" : "operation",
    "type" : [ {
      "type" : "record",
      "name" : "OperationOnEntry",
      "fields" : [ ... ]
    }, {
      "type" : "enum",
      "name" : "Read",
      "symbols" : [ "Read" ]
    } ]
  }

Is it possible to represent this type in Kotlin using Avro4k? I tried

@Serializable
sealed class Operation
@Serializable
data class OperationOnEntry( ... ) : Operation()
@Serializable
object Read : Operation()

However this produces

{
    "name" : "operation",
    "type" : [ {
      "type" : "record",
      "name" : "OperationOnEntry",
      "fields" : [ ... ]
    }, {
      "type" : "record",
      "name" : "Read",
      "fields" : [ ]
    } ]
  }
thake commented 2 years ago

Right now this is afaik not possible to represent. Avro4k does currently not support open polymorphic references (see https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#open-polymorphism).

This would be needed to serialize the following data structure which would matches the first mentioned schema:

interface Operation
@Serializable
data class OperationOnEntry( ... ) : Operation
@Serializable
enum class Read : Operation {
    Read
}
thake commented 2 years ago

This is now possible with the support of polymorphic classes #110