Skip to content

Commit

Permalink
Add Result#toErrorUnless
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbull committed Apr 18, 2020
1 parent 22898ff commit 1000c58
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/main/kotlin/com/github/michaelbull/result/Map.kt
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ inline infix fun <V, E, U> Result<V, E>.flatMap(transform: (V) -> Result<U, E>):
/**
* Returns the [transformation][transform] of the [value][Ok.value] if this [Result] is [Ok]
* and satisfies the given [predicate], otherwise this [Result].
*
* @see [takeIf]
*/
inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, transform: (V) -> E): Result<V, E> {
contract {
Expand All @@ -186,3 +188,25 @@ inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, transform: (
is Err -> this
}
}

/**
* Returns the [transformation][transform] of the [value][Ok.value] if this [Result] is [Ok]
* and _does not_ satisfy the given [predicate], otherwise this [Result].
*
* @see [takeUnless]
*/
inline fun <V, E> Result<V, E>.toErrorUnless(predicate: (V) -> Boolean, transform: (V) -> E): Result<V, E> {
contract {
callsInPlace(predicate, InvocationKind.AT_MOST_ONCE)
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}

return when (this) {
is Ok -> if (!predicate(value)) {
Err(transform(value))
} else {
this
}
is Err -> this
}
}

0 comments on commit 1000c58

Please sign in to comment.