Skip to content

Commit

Permalink
Merge pull request #4436 from Daenyth/either-raisewhen
Browse files Browse the repository at this point in the history
Add `raiseWhen`/`raiseUnless` convenience methods to `EitherObjectOps`
  • Loading branch information
danicheg authored May 13, 2023
2 parents 8486e32 + 2eeb0a5 commit 8473a37
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
24 changes: 24 additions & 0 deletions core/src/main/scala/cats/syntax/either.scala
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,30 @@ final class EitherObjectOps(private val either: Either.type) extends AnyVal {
* Cached value of `Right(())` to avoid allocations for a common case.
*/
def unit[A]: Either[A, Unit] = EitherUtil.unit

/**
* Returns `Left(ifTrue)` when the `cond` is true, otherwise `Right(())`
*
* @example {{{
* val tooMany = 5
* val x: Int = ???
* Either.raiseWhen(x >= tooMany)(new IllegalArgumentException("Too many"))
* }}}
*/
def raiseWhen[A](cond: Boolean)(ifTrue: => A): Either[A, Unit] =
ApplicativeError[Either[A, *], A].raiseWhen(cond)(ifTrue)

/**
* Returns `Left(ifFalse)` when `cond` is false, otherwise `Right(())`
*
* @example {{{
* val tooMany = 5
* val x: Int = ???
* Either.raiseUnless(x < tooMany)(new IllegalArgumentException("Too many"))
* }}}
*/
def raiseUnless[A](cond: Boolean)(ifFalse: => A): Either[A, Unit] =
ApplicativeError[Either[A, *], A].raiseUnless(cond)(ifFalse)
}

final class LeftOps[A, B](private val left: Left[A, B]) extends AnyVal {
Expand Down
10 changes: 10 additions & 0 deletions tests/shared/src/test/scala/cats/tests/EitherSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,16 @@ class EitherSuite extends CatsSuite {
assert(either.leftFlatMap(f) === (either.swap.flatMap(a => f(a).swap).swap))
}
}

test("raiseWhen raises when true") {
val result = Either.raiseWhen(true)("ok")
assert(result === Left("ok"))
}

test("raiseUnless raises when false") {
val result = Either.raiseUnless(false)("ok")
assert(result === Left("ok"))
}
}

final class EitherInstancesSuite extends munit.FunSuite {
Expand Down

0 comments on commit 8473a37

Please sign in to comment.