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
.
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.