Skip to content

Instantly share code, notes, and snippets.

@ploddi
Last active August 29, 2015 14:18
Show Gist options
  • Save ploddi/8ef2b906286117af4971 to your computer and use it in GitHub Desktop.
Save ploddi/8ef2b906286117af4971 to your computer and use it in GitHub Desktop.
HList Reads
/**
* Based on
* https://github.com/mandubian/shapelaysson/blob/master/src/main/scala/shapelaysson.scala
*/
package object test {
import shapeless._
import shapeless.HList._
import play.api.libs.json._
import play.api.libs.functional.Functor
import play.api.libs.functional.syntax._
import scala.{:: => ::|}
private implicit val `JsResult Functor` = new Functor[JsResult] {
def fmap[A, B](m: JsResult[A], f: (A) => B) = m.map(f)
}
implicit def hlistReads[H : Reads, T <: HList : Reads]: Reads[H :: T] = Reads {
_.validate[JsArray].map(_.value.toList).flatMap {
case head ::| tail => (head.validate[H] ~ JsArray(tail).validate[T])(_ :: _)
case _ => JsError("can't convert empty list using multi-element HList")
}
}
implicit def hnilReads: Reads[HNil] = Reads {
case JsArray(values) if values.isEmpty => JsSuccess(HNil)
case _ => JsError("Not empty JsArray")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment