Add getOrThrow

Closes #68
This commit is contained in:
Sebastian Kappen 2022-01-01 13:22:40 +01:00 committed by Michael Bull
parent e5c47a46b5
commit d07bd589ed
2 changed files with 72 additions and 0 deletions

View File

@ -121,6 +121,39 @@ public inline infix fun <V, E> Result<V, E>.getErrorOrElse(transform: (V) -> E):
} }
} }
/**
* Returns the [value][Ok.value] if this [Result] is [Ok], otherwise throws the
* [error][Err.error].
*
* This is functionally equivalent to [`getOrElse { throw it }`][getOrElse].
*/
public fun <V, E : Throwable> Result<V, E>.getOrThrow(): V {
contract {
returns() implies (this@getOrThrow is Ok<V>)
}
return when (this) {
is Ok -> value
is Err -> throw error
}
}
/**
* Returns the [value][Ok.value] if this [Result] is [Ok], otherwise throws the
* [transformation][transform] of the [error][Err.error] to a [Throwable].
*/
public inline infix fun <V, E> Result<V, E>.getOrThrow(transform: (E) -> Throwable): V {
contract {
returns() implies (this@getOrThrow is Ok<V>)
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Ok -> value
is Err -> throw transform(error)
}
}
/** /**
* Merges this [Result<V, E>][Result] to [U], returning the [value][Ok.value] if this [Result] is [Ok], otherwise the * Merges this [Result<V, E>][Result] to [U], returning the [value][Ok.value] if this [Result] is [Ok], otherwise the
* [error][Err.error]. * [error][Err.error].

View File

@ -2,6 +2,7 @@ package com.github.michaelbull.result
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertEquals import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull import kotlin.test.assertNull
@Suppress("IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION") @Suppress("IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION")
@ -54,6 +55,44 @@ class GetTest {
} }
} }
class GetOrThrow {
@Test
fun returnsValueIfOk() {
assertEquals(
expected = "hello",
actual = Ok("hello").getOrThrow()
)
}
@Test
fun throwsErrorIfErr() {
assertFailsWith<CustomException> {
Err(CustomException()).getOrThrow()
}
}
class CustomException : Throwable()
}
class GetOrThrowWithTransform {
@Test
fun returnsValueIfOk() {
assertEquals(
expected = "hello",
actual = Ok("hello").getOrThrow { CustomException("Failed") }
)
}
@Test
fun throwsTransformedErrorIfErr() {
assertFailsWith<CustomException> {
Err("error").getOrThrow { error -> CustomException(error) }
}
}
class CustomException(message: String) : Throwable(message)
}
class GetErrorOr { class GetErrorOr {
@Test @Test
fun returnsDefaultValueIfOk() { fun returnsDefaultValueIfOk() {