Warm tip: This article is reproduced from serverfault.com, please click

How to define and pass implicit encoder of a particular subtype to AvroSchema

发布于 2020-11-12 09:50:30

Is it possible to define and pass Encoder[E] for any subtype E (e.g. any E that extends GeneratedEnum class, in the code instance of E is Color) to AvroSchema[C] where C is some case class that contains E as field.

case class Color(value: Int) extends scalapb.GeneratedEnum // ... it has .name field
case class MyCaseClassWithEnum(color: Color) // ...

implicit def enumEncoder[E <: scalapb.GeneratedEnum]: Encoder[E] = new Encoder[E] {
  override def encode(e: E, schema: Schema, fieldMapper: FieldMapper): AnyRef = e.name
}

val actualSchema = AvroSchema[MyCaseClassWithEnum]

The full source code is here

Basically would like that any subtype instance of GeneratedEnum like Color encodes as String.

Questioner
fpopic
Viewed
11
Dmytro Mitin 2020-11-29 04:50:06

Try to define

implicit val schemaForColor: SchemaFor[Color] = new SchemaFor[Color]() {
  override def schema(fieldMapper: FieldMapper): Schema = 
    SchemaHelper.matchPrimitiveName("java.lang.String").get
}

or

implicit def schemaForColor[E <: GeneratedEnum]: SchemaFor[E] = new SchemaFor[E]() {
  override def schema(fieldMapper: FieldMapper): Schema =
    SchemaHelper.matchPrimitiveName("java.lang.String").get
}

Then the test MyCaseClassWithEnumTest passes.