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

Introduces throwIf and throwUnless #66

Closed
wants to merge 2 commits into from
Closed
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
@@ -0,0 +1,27 @@
package com.github.michaelbull.result

import kotlin.contracts.InvocationKind
import kotlin.contracts.contract

/**
* If the [Result] is [Err] and contains a [Throwable], throws the [error][Err.error]
* if the [predicate] returns true.
*
* @throws E if [predicate] returns true.
*/
public inline fun <V : Any?, E : Throwable> Result<V, E>.throwIf(
predicate: (E) -> Boolean
): Result<V, E> {
contract { callsInPlace(predicate, InvocationKind.AT_MOST_ONCE) }
return onFailure { e -> if (predicate(e)) throw e }
}

/**
* If the [Result] is [Err] and contains a [Throwable], throws the [error][Err.error]
* only if the [predicate] returns false.
*
* @throws E if [predicate] returns false.
*/
public inline fun <V : Any?, E : Throwable> Result<V, E>.throwUnless(
predicate: (E) -> Boolean
): Result<V, E> = throwIf { e -> predicate(e).not() }
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.github.michaelbull.result

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

class ThrowTest {

class ThrowIfTest {
@Test
fun throwsIfPredicateReturnsTrue() {
val result: Result<Any, Throwable> = Err(RuntimeException())

assertFailsWith<RuntimeException> {
result.throwIf { _ -> true }
}
}

@Test
fun nothingThrownIfPredicateReturnsFalse() {
val result: Result<Any, Exception> = Err(NullPointerException())

result.throwIf { _ -> false }
}

@Test
fun doesntAlterOkValue() {
val result: Result<String, Throwable> = Ok("ok")

assertEquals(
expected = "ok",
actual = result.throwIf(predicate = { false }).unwrap()
)
}
}

class ThrowUnlessTest {
@Test
fun throwsIfPredicateReturnsFalse() {
val result: Result<Any, Throwable> = Err(RuntimeException())

assertFailsWith<RuntimeException> {
result.throwUnless { _ -> false }
}
}

@Test
fun nothingThrownIfPredicateReturnsTrue() {
val result: Result<Any, Exception> = Err(NullPointerException())

result.throwUnless { _ -> true }
}

@Test
fun doesntAlterOkValue() {
val result: Result<String, Throwable> = Ok("ok")

assertEquals(
expected = "ok",
actual = result.throwUnless(predicate = { false }).unwrap()
)
}
}
}