Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -1344,6 +1344,32 @@ public inline infix fun <A, B> Either<A, B>.getOrElse(default: (A) -> B): B {
}
}

/**
* Returns the right value [B] of this [Either],
* or throws an exception produced by applying the [onLeft] function to the left value [A].
*
* ```kotlin
* import arrow.core.Either
* import arrow.core.getOrElseThrow
* import io.kotest.assertions.throwables.shouldThrow
* import io.kotest.matchers.shouldBe
*
* fun test() {
* Either.Right(12).getOrElseThrow { RuntimeException("Error: $it") } shouldBe 12
* shouldThrow<RuntimeException> {
* Either.Left("error").getOrElseThrow { RuntimeException("Error: $it") }
* }.message shouldBe "Error: error"
* }
* ```
*/
public inline fun <A, B> Either<A, B>.getOrElseThrow(onLeft: (A) -> Throwable): B {
contract { callsInPlace(onLeft, InvocationKind.AT_MOST_ONCE) }
return when (this) {
is Left -> throw onLeft(this.value)
is Right -> this.value
}
}

/**
* Returns the value from this [Right] or [Left].
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,21 @@ class EitherTest {
Left(a).getOrElse { b } shouldBe b
}
}

@Test
fun getOrElseThrowOk() = runTest {
checkAll(Arb.int()) { a: Int ->
Right(a).getOrElseThrow { RuntimeException("Error: $it") } shouldBe a

val left: Either<String, Int> = Left("error")
try {
left.getOrElseThrow { RuntimeException("Error: $it") }
fail("Should have thrown an exception")
} catch (e: RuntimeException) {
e.message shouldBe "Error: error"
}
}
}

@Test
fun getOrNullOk() = runTest {
Expand Down
Loading