如何定义特定子类型的隐式编码器并将其传递给 AvroSchema
How to define and pass implicit encoder of a particular subtype to AvroSchema
是否可以为任何子类型 E
定义和传递 Encoder[E]
(例如,在代码实例中扩展 GeneratedEnum
class 的任何 E
E
是 Color
) 到 AvroSchema[C]
其中 C
是某种情况 class 包含 E
作为字段。
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]
完整的源代码是here
基本上希望 GeneratedEnum
的任何子类型实例像 Color
编码为 String
.
尝试定义
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
通过。
是否可以为任何子类型 E
定义和传递 Encoder[E]
(例如,在代码实例中扩展 GeneratedEnum
class 的任何 E
E
是 Color
) 到 AvroSchema[C]
其中 C
是某种情况 class 包含 E
作为字段。
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]
完整的源代码是here
基本上希望 GeneratedEnum
的任何子类型实例像 Color
编码为 String
.
尝试定义
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
通过。