Play JSON InvariantFunctor

JSON playback library includes Functorand Invariant Functor:

I have seen Functorbefore:

trait Functor[M[_]] extends Variant[M] {

  def fmap[A, B](m: M[A], f: A => B): M[B]

}

But, conceptually, why do we need to provide both functions f1and f2for InvariantFunctor?

trait InvariantFunctor[M[_]] extends Variant[M] {

  def inmap[A, B](m: M[A], f1: A => B, f2: B => A): M[B]

}
+4
source share
1 answer

In this answer, I give a brief explanation of why Writesit is not a functor, i.e. why, if we have a Writes[A]function and A => Bwe can not create the Writes[B]same as with Reads.

, Writes () , , , a Writes[A] B => A, a Writes[B].

Format Reads, Writes, , , - ( , Play).

, , , :

case class Foo(i: Int, s: String)
case class Bar(s: String, i: Int)

, Format Foo:

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

implicit val fooFormat = Json.format[Foo]

- Bar - Foo. , Bar Foo, , , Format:

implicit val barFormat = fooFormat.inmap[Bar](
  foo => Bar(foo.s, foo.i),
  bar => Foo(bar.i, bar.s)
)

, Format , JsValue A, A JsValue. Format[A] Format[B], (.. A => B, B => A).

+11

All Articles