Skip to content

Commit

Permalink
Add getOrThrow
Browse files Browse the repository at this point in the history
Closes #68
  • Loading branch information
Nimelrian authored and michaelbull committed Jan 8, 2022
1 parent e5c47a4 commit d07bd58
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
* [error][Err.error].
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.github.michaelbull.result

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull

@Suppress("IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION")
Expand Down Expand Up @@ -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 {
@Test
fun returnsDefaultValueIfOk() {
Expand Down

0 comments on commit d07bd58

Please sign in to comment.