Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make type renaming shorter #62

Open
Stefanqn opened this issue Sep 24, 2018 · 0 comments
Open

make type renaming shorter #62

Stefanqn opened this issue Sep 24, 2018 · 0 comments

Comments

@Stefanqn
Copy link

It seems like a lot of code just to e.g. rename Left and Right in Either:

  def eitherFormat[L: Format, R: Format](typeMap: Map[String, String] = Map("Left" -> "Error", "Right" -> "Ok"))(
      implicit
      derivedReads: Lazy[DerivedReads[Either[L, R]]],
      derivedOWrites: Lazy[DerivedOWrites[Either[L, R]]]): OFormat[Either[L, R]] = {
    type A = Either[L, R]
    val adapter = NameAdapter.identity

    def eitherTypeTagReads(map: Map[String, String]): TypeTagReads =
      new TypeTagReads {
        def reads[A](typeName: String, reads: Reads[A]): Reads[A] =
          (__ \ map.getOrElse(typeName, typeName)).read(reads)
      }

    def eitherTypeTagOWrites(map: Map[String, String]): TypeTagOWrites =
      new TypeTagOWrites {
        def owrites[A](typeName: String, owrites: OWrites[A]): OWrites[A] =
          OWrites[A](a => Json.obj(map.getOrElse(typeName, typeName) -> owrites.writes(a)))
      }

    OFormat[A](
      derivedReads.value.reads(eitherTypeTagReads(typeMap), adapter),
      derivedOWrites.value.owrites(eitherTypeTagOWrites(typeMap), adapter))
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant