Skip to content

Instantly share code, notes, and snippets.

@arosien
Last active August 29, 2015 14:20
Show Gist options
  • Save arosien/51532a52299e7c698012 to your computer and use it in GitHub Desktop.
Save arosien/51532a52299e7c698012 to your computer and use it in GitHub Desktop.
// JsonFormat is from spray-json, reproduced here
trait JsonFormat[A] {
def write(a: A): JsValue
def read(js: JsValue): A
}
implicit class FormatInvariantFunctor[A](format: JsonFormat[A]) {
def xmap[B](f: A => B, g: B => A): JsonFormat[B] =
new JsonFormat[B] {
def write(b: B): JsValue = format.write(g(b))
def read(js: JsValue): B = f(format.read(js))
}
// is there a name for this?
def using[B](f: A => B, g: B => A)(J: JsonFormat[B]): JsonFormat[A] =
new JsonFormat[A] {
def write(a: A): JsValue = J.write(f(a))
def read(js: JsValue): A = g(J.read(js))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment