Skip to content

Commit

Permalink
Merge pull request #600 from ceedubs/option-show
Browse files Browse the repository at this point in the history
Add Show for Option and OptionT
  • Loading branch information
non committed Nov 8, 2015
2 parents acd02bb + f0497b5 commit f20f021
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
5 changes: 5 additions & 0 deletions core/src/main/scala/cats/data/OptionT.scala
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ final case class OptionT[F[_], A](value: F[Option[A]]) {

def toLeft[R](right: => R)(implicit F: Functor[F]): XorT[F, A, R] =
XorT(cata(Xor.Right(right), Xor.Left.apply))

def show(implicit F: Show[F[Option[A]]]): String = F.show(value)
}

object OptionT extends OptionTInstances {
Expand Down Expand Up @@ -138,4 +140,7 @@ private[data] sealed trait OptionTInstances extends OptionTInstances1 {
}
implicit def optionTEq[F[_], A](implicit FA: Eq[F[Option[A]]]): Eq[OptionT[F, A]] =
FA.on(_.value)

implicit def optionTShow[F[_], A](implicit F: Show[F[Option[A]]]): Show[OptionT[F, A]] =
functor.Contravariant[Show].contramap(F)(_.value)
}
8 changes: 8 additions & 0 deletions core/src/main/scala/cats/std/option.scala
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,14 @@ trait OptionInstances extends OptionInstances1 {
if (y.isDefined) -1 else 0
}
}

implicit def showOption[A](implicit A: Show[A]): Show[Option[A]] =
new Show[Option[A]] {
def show(fa: Option[A]): String = fa match {
case Some(a) => s"Some(${A.show(a)})"
case None => "None"
}
}
}

private[std] sealed trait OptionInstances1 extends OptionInstances2 {
Expand Down
5 changes: 5 additions & 0 deletions tests/src/test/scala/cats/tests/OptionTTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ class OptionTTests extends CatsSuite {
}
}

test("show"){
val xor: String Xor Option[Int] = Xor.right(Some(1))
OptionT[Xor[String, ?], Int](xor).show should === ("Xor.Right(Some(1))")
}

checkAll("OptionT[List, Int]", MonadCombineTests[OptionT[List, ?]].monad[Int, Int, Int])
checkAll("MonadOptionT[List, ?]]", SerializableTests.serializable(Monad[OptionT[List, ?]]))

Expand Down
9 changes: 9 additions & 0 deletions tests/src/test/scala/cats/tests/OptionTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,13 @@ class OptionTests extends CatsSuite {

checkAll("Option[Int] with Option", TraverseTests[Option].traverse[Int, Int, Int, Int, Option, Option])
checkAll("Traverse[Option]", SerializableTests.serializable(Traverse[Option]))

test("show") {
none[Int].show should === ("None")
1.some.show should === ("Some(1)")

forAll { fs: Option[String] =>
fs.show should === (fs.toString)
}
}
}

0 comments on commit f20f021

Please sign in to comment.