Add Result#toErrorUnless
Gives us symmetry with the kotlin stdlib: - https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/take-if.html - https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/take-unless.html
This commit is contained in:
parent
22898fff4f
commit
1000c588c0
@ -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]
|
* Returns the [transformation][transform] of the [value][Ok.value] if this [Result] is [Ok]
|
||||||
* and satisfies the given [predicate], otherwise this [Result].
|
* 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> {
|
inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, transform: (V) -> E): Result<V, E> {
|
||||||
contract {
|
contract {
|
||||||
@ -186,3 +188,25 @@ inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, transform: (
|
|||||||
is Err -> this
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user