Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add raiseWhen/raiseUnless convenience methods to EitherObjectOps #4436

Merged
merged 2 commits into from
May 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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