Skip to content

Commit

Permalink
Add attemptTap example
Browse files Browse the repository at this point in the history
  • Loading branch information
Raas Ahsan committed Jun 16, 2020
1 parent 00651a7 commit 6b462db
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
16 changes: 11 additions & 5 deletions core/src/main/scala/cats/MonadError.scala
Original file line number Diff line number Diff line change
Expand Up @@ -88,17 +88,23 @@ trait MonadError[F[_], E] extends ApplicativeError[F, E] with Monad[F] {
* scala> import cats.implicits._
* scala> import scala.util.{Try, Success}
*
* scala> def logErrors(result: Either[Throwable, Int]): Try[Unit] =
*
* scala> val a: Try[Either[Throwable, Int]] = Success(Left(new java.lang.Exception))
* scala> def logErrors(result: Either[Throwable, Int]): Try[Unit] = Try {
* result match {
* case Right(value) => println(s"Success: $value")
* case Left(_) => println("Failed")
* }
* }
*
* scala> val a: Try[Int] = Success(new java.lang.Exception)
* scala> a.attemptTap(logErrors)
* Failed
* res0: scala.util.Try[Int] = Failure(java.lang.Exception)
*
* scala> val b: Try[Either[Throwable, Int]] = Success(Right(1))
* scala> val b: Try[Int] = Success(1)
* scala> b.attemptTap(logErrors)
* Success: 1
* res1: scala.util.Try[Int] = Success(1)
* }}}
*
*/
def attemptTap[A, B](fa: F[A])(f: Either[E, A] => F[B]): F[A] =
rethrow(flatTap(attempt(fa))(f))
Expand Down
3 changes: 3 additions & 0 deletions core/src/main/scala/cats/syntax/monadError.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ final class MonadErrorOps[F[_], E, A](private val fa: F[A]) extends AnyVal {

def redeemWith[B](recover: E => F[B], bind: A => F[B])(implicit F: MonadError[F, E]): F[B] =
F.redeemWith[A, B](fa)(recover, bind)

def attemptTap[B](f: Either[E, A] => F[B])(implicit F: MonadError[F, E]): F[A] =
F.attemptTap(fa)(f)
}

final class MonadErrorRethrowOps[F[_], E, A](private val fea: F[Either[E, A]]) extends AnyVal {
Expand Down

0 comments on commit 6b462db

Please sign in to comment.