Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.