Add Result#toError

Facilitates transforming an Ok to an Err if the value satisfies a given
prdicate.
This commit is contained in:
Markus Padourek 2020-02-16 20:48:47 +01:00 committed by Michael Bull
parent 4d2a2d1453
commit cf9582075d

View File

@ -166,3 +166,18 @@ inline infix fun <V, E, U> Result<V, E>.flatMap(transform: (V) -> Result<U, E>):
return andThen(transform) return andThen(transform)
} }
/**
* Returns the [transformation][transform] of the [value][Ok.value] if this [Result] is [Ok]
* and satisfies the given [predicate], otherwise this [Result].
*/
inline fun <V, E> Result<V, E>.toErrorIf(predicate: (V) -> Boolean, transform: (V) -> E): Result<V, E> {
return when (this) {
is Ok -> if (predicate(value)) {
Err(transform(value))
} else {
this
}
is Err -> this
}
}