title: Scala - JSON object is polymorphic on a field type
body: <p>I'm attempting to decode some truly terrible JSON. The type information for each object is encoded within a field labeled <code>type</code> , i.e. <code>"type": "event"</code>, etc. I'm using <a href="https://github.com/travisbrown/circe/" rel="nofollow">Circe</a> for JSON encoding / decoding.  The library utilizes typeclasses, where the relevant typeclass is <code>def apply(c: HCursor): Decoder.Result[A]</code>.  The issue is that any Decoder is invariant to type, <code>A</code>.  Here is a concrete example</p>
  
  <pre><code>sealed trait MotherEvent {
    val id: UUID
    val timestamp: DateTime
  }
  implicit val decodeJson: Decoder[MotherEvent] = new Decoder[MotherEvent] { 
  def apply(c: HCursor) = {
    c.downField("type").focus match {
      case Some(x) =&gt; x.asString match {
        case Some(string) if string == "flight" =&gt; FlightEvent.decodeJson(c)
        case Some(string) if string == "hotel"  =&gt; // etc 
        // like a bunch of these
        case None =&gt; Xor.Left(DecodingFailure("type is not a string", c.history))
      }
      case None    =&gt; Xor.Left(DecodingFailure("not type found", c.history))
    }
  }
  
  sealed trait FlightEvents(id: UUID, timestamp: DateTime, flightId: Int)
  case class Arrival(id: UUID, timestamp: DateTime, flightId: Int) extends Event // a metric ton of additional fields
  case class Departure(id: UUID, timestamp: DateTime, flightId: Int) extends Event // samsies as Arrival
  </code></pre>
  
  <p>Decoding works fine, but <code>MotherEvent</code> is always returned</p>
  
  <pre><code>val jsonString = // from wherevs, where the json string is flightevent
  val x = decode[MotherEvent](jsonString)
  println(x) // prints (cats.data.Xor[io.circe.Error, MotherEvent] = Right(FlightEvent)
  println(x.flightId) // ERROR- flightId is not a member of MotherEvent
  </code></pre>
  
  <p>Of course, I would like to have a FlightEvent instead of mother event. One possible solution is to create a "mother" type that has 60 or 70 fields, but I already hate myself and want to quit programming just thinking about 70 <code>Option[A]</code> fields that are filled based off the <code>type</code> field.</p>
  
  <p>Can anyone think of a good solution to this? </p>