1

Suppose I have a class hierarchy like:

trait Event
case class ThisEvent extends Event
case class ThatEvent extends Event
case class AnotherEvent extends Event

Currently in my serialization code I have to use this:

implicit val formats = new DefaultFormats {
  override val typeHintFieldName = "_t"
  override val typeHints = ShortTypeHints(List(classOf[ThisEvent], classOf[ThatEvent], classOf[AnotherEvent]))
}

But I would very much prefer something like this:

implicit val formats = new DefaultFormats {
  override val typeHintFieldName = "_t"
  override val typeHints = ShortTypeHints(List(classOf[Event]))
}

How would you solve this?

Kostassoid
  • 1,870
  • 2
  • 20
  • 29

1 Answers1

1

If you can make Event a sealed trait, then you can use the macro explained here to iterate over its subclasses, by introducing the SealedExample object with the desired helper method. The example only gets objects that extend the sealed trait, but you could easily modify it to return the classOf of every subclass. Then you can do:

override val typeHints = ShortTypeHints(SealedExample.values[Event].toList)

Otherwise, unfortunately, there is no native way in Scala to generate a list of the subtypes of a trait at compile time.

Community
  • 1
  • 1
Ben Reich
  • 16,222
  • 2
  • 38
  • 59