I am trying to define an avro4s schema derivation for a common trait. Example
trait Event
case class UserCreated(name: String, age: Int) extends Event
case class UserDeleted(reason: String) extends Event
Derivation for the concrete classes seems straightforward:
given userCreatedSchemaFor = SchemaFor[UserCreated]
given userDeletedSchemaFor = SchemaFor[UserDeleted]
I would love to achieve something like this fake code:
given eventSchemaFor = new SchemaFor[Event] {
CASE (userCreated) => USE userCreatedSchemaFor
CASE (userDeleted) => USE userDeletedSchemaFor
}
The SchemaFor trait & object expose some apply variants and 'factory' methods but I can't figure out a way to use them to my purpose. Thanks for any help.
The answer by @stefanobaghino is correct if you can seal the trait, but in my case I was interested in an unsealed trait. The solution to generate a schema was quite near - avro4s provides a
Schema.createUnionwhich is great for this usecase.The next problem you might have is encoding for serialization (after all we want to do something useful with this data). For that, the best way I found was the manual creation of an Encoder. Follows a scala-cli script that shows everything put together.