Skip to content

Instantly share code, notes, and snippets.

@realpeterz
realpeterz / SingleFieldFormat.scala
Last active July 24, 2021 01:28
Play Json Format helper for value classes
import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, Json}
object SingleFieldFormat {
def format[A, B](f: A => B, g: B => A)(implicit fa: Format[A]) = fa.inmap(f, g)
// expanded:
// syntax.toInvariantFunctorOps(fa)(Format.invariantFunctorFormat).inmap(f, g)
// inmap's underlying:
// Format[B](fa.map(f), Writes[B](b => fa.writes(g(b))))
}
@realpeterz
realpeterz / AdtFormat.scala
Created February 14, 2018 19:17
Generic Play Json ADT Format (Writes & Reads)
import play.api.libs.json._
import scala.reflect.ClassTag
trait AdtFormat[A <: Product with Serializable] {
type ReadByTypeFunc[C <: A] = PartialFunction[String, JsResult[C]]
type ReadsFunc[B <: A] = JsValue => JsResult[B]
type WriteFunc = PartialFunction[A, JsValue]