0

Encoder[E]是否可以为任何子类型E(例如,在is的代码实例中E扩展GeneratedEnum类的任何子类型)定义和传递到where是包含as 字段的某个案例类。EColorAvroSchema[C]CE

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]

完整的源代码在这里

基本上希望 like 的任何子类型实例都GeneratedEnum编码ColorString.

4

1 回答 1

1

尝试定义

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

或者

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

然后测试MyCaseClassWithEnumTest通过。

于 2020-11-28T20:38:01.000 回答