Skip to content

Instantly share code, notes, and snippets.

@phadej
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phadej/c60912802dc494c3212b to your computer and use it in GitHub Desktop.
Save phadej/c60912802dc494c3212b to your computer and use it in GitHub Desktop.

Suppose we extend the example in Travis' answer:

sealed trait Foo { def name: String }
case class Bar(name: String, i: Int) extends Foo
case class Baz(name: String, c: Char) extends Foo

import play.api.libs.functional.syntax._
import play.api.libs.json._

implicit val readsBar: Reads[Bar] = (
  (__ \ 'name).read[String] and (__ \ 'i).read[Int]
)(Bar.apply _)

implicit val readsBaz: Reads[Baz] = (
  (__ \ 'name).read[String] and (__ \ 'c).read[Char]
 )(Baz.apply _)

implicit val readsFoo: Reads[Foo] = readsBar.map(x => x).orElse(readsBaz.map(x => x))

I have to provide to x => x identity function to upcast Bar and Baz inside the Reads.

So to clarify, do I have to use .map(x => x) to upcast the Reads[Bar] and Reads[Baz] into Reads[Foo] or how I should write a Reads[Foo] instance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment