Skip to content

Commit

Permalink
Change MonadErrorOps#reject so it no longer runs effects twice (#2810)
Browse files Browse the repository at this point in the history
* Add regression test for MonadErrorOps bug

* Change MonadErrorOps#reject so it no longer re-runs the effect it is called on. Fixes #2809
  • Loading branch information
Ben Plommer authored and kailuowang committed Apr 25, 2019
1 parent a6723ac commit 0d6aafc
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
2 changes: 1 addition & 1 deletion core/src/main/scala/cats/syntax/monadError.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ final class MonadErrorOps[F[_], E, A](private val fa: F[A]) extends AnyVal {
*/
def reject(pf: PartialFunction[A, E])(implicit F: MonadError[F, E]): F[A] =
F.flatMap(fa) { a =>
pf.andThen(F.raiseError[A] _).applyOrElse(a, (_: A) => fa)
pf.andThen(F.raiseError[A] _).applyOrElse(a, F.pure)
}

def adaptError(pf: PartialFunction[E, E])(implicit F: MonadError[F, E]): F[A] =
Expand Down
6 changes: 5 additions & 1 deletion tests/src/test/scala/cats/tests/RegressionSuite.scala
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cats
package tests

import cats.data.{Const, NonEmptyList}
import cats.data.{Const, NonEmptyList, StateT}
import scala.collection.mutable
import scala.collection.immutable.SortedMap
class RegressionSuite extends CatsSuite {
Expand Down Expand Up @@ -157,4 +157,8 @@ class RegressionSuite extends CatsSuite {

}

test("#2809 MonadErrorOps.reject runs effects only once") {
val program = StateT.modify[Either[Throwable, ?], Int](_ + 1).reject { case _ if false => new Throwable }
program.runS(0).right.get should ===(1)
}
}

0 comments on commit 0d6aafc

Please sign in to comment.