Skip to content

Commit

Permalink
Implement JsonWriter for Either
Browse files Browse the repository at this point in the history
  • Loading branch information
REDNBLACK committed Jan 25, 2021
1 parent 1245f44 commit 227b5a9
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package tethys.writers.instances
import tethys.JsonWriter
import tethys.writers.tokens.TokenWriter

trait AllJsonWriters extends OptionWriters {
trait AllJsonWriters extends OptionWriters with EitherWriters {
implicit lazy val intWriter: JsonWriter[Int] = new JsonWriter[Int] {
override def write(value: Int, tokenWriter: TokenWriter): Unit = tokenWriter.writeNumber(value)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package tethys.writers.instances

import tethys.JsonWriter
import tethys.writers.tokens.TokenWriter

private[tethys] trait EitherWriters {
implicit def eitherWriter[L, R](implicit L: JsonWriter[L], R: JsonWriter[R]): JsonWriter[Either[L, R]] = new JsonWriter[Either[L, R]] {
override def write(name: String, value: Either[L, R], tokenWriter: TokenWriter): Unit = {
value match {
case Left(left) => L.write(name, left, tokenWriter)
case Right(right) => R.write(name, right, tokenWriter)
}
}

def write(value: Either[L, R], tokenWriter: TokenWriter): Unit = {
value match {
case Left(left) => L.write(left, tokenWriter)
case Right(right) => R.write(right, tokenWriter)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ class DefaultWritersTest extends AnyFlatSpec {
test(Map("a" -> 1, "b" -> 2)) -> obj("a" -> 1, "b" -> 2),
test(Option(1), "Option.nonEmpty") -> value(1),
test(Option.empty[Int], "Option.empty") -> List(NullValueNode),
test(Right(1): Either[String, Int], "Either.right") -> value(1),
test(Left("Not an Int"): Either[String, Int], "Either.left") -> value("Not an Int"),
test(1: java.lang.Integer) -> value(1),
test(java.lang.Short.valueOf(1: Short)) -> value(1: Short),
test(1L: java.lang.Long) -> value(1L),
Expand Down

0 comments on commit 227b5a9

Please sign in to comment.