1

I have a simple type hierarchy like the following:

  sealed abstract class Config
  object Config {
    case class Valid(name: String, traits: List[String]) extends Config
    case class Invalid(error: String) extends Config
  }
  implicit val validFormat = jsonFormatFor(Config.Valid)
  implicit val invalidFormat = jsonFormatFor(Config.Invalid)

I also have client code that does the following:

newHttpServer().addHandler("/config", extractConfig)

The extractConfig method performs some computations and returns either a Config.Valid or a Config.Invalid, which the server will automatically convert to json by using the implicit json format objects. My problem is that there is a compiler error because extractConfig returns a Config:

type mismatch; found : Config 
     required: spray.httpx.marshalling.ToResponseMarshallable

If I change the return type of extractConfig to Config.Valid then the server code compiles because jsonFormatFor(...) supplies the necessary automatic type conversion to make the respose a ToResponseMarshaller (though I admit I don't fully understand this automatic conversion as well, being somewhat new to scala). Is there a simple way to solve this by declaring that any subclass of Config must be a ToResponseMarshaller, given that ToResponseMarshaller is a trait that seems to be supplied via implicit conversions?

jonderry
  • 23,013
  • 32
  • 104
  • 171
  • You should say which JSON library you're using. LiftJSON, e.g., allows you to give hint about abstract types to be deserialized / unmarshalled. Check here for how that works… http://stackoverflow.com/questions/7525875/polymorphic-lift-json-deserialization-in-a-composed-class – Randall Schulz Jun 17 '14 at 02:14
  • I'm using spray/spray-json – jonderry Jun 17 '14 at 03:08

1 Answers1

2

If you only have Config.Valid and Config.Invalid it should be sufficient that extractConfig returns an Either[Config.Valid, Config.Invalid]. Then your formats above should work.

Another possibility is to write your own jsonwriter (see this thread from the mailing list).

Christian
  • 4,543
  • 1
  • 22
  • 31