From 1000c588c01a6f1fa9133329c11681ecda112a95 Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Sat, 18 Apr 2020 11:48:45 +0100 Subject: [PATCH] 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 --- .../com/github/michaelbull/result/Map.kt | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/main/kotlin/com/github/michaelbull/result/Map.kt b/src/main/kotlin/com/github/michaelbull/result/Map.kt index fcf419e..7efaf2f 100644 --- a/src/main/kotlin/com/github/michaelbull/result/Map.kt +++ b/src/main/kotlin/com/github/michaelbull/result/Map.kt @@ -170,6 +170,8 @@ inline infix fun Result.flatMap(transform: (V) -> Result): /** * 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 Result.toErrorIf(predicate: (V) -> Boolean, transform: (V) -> E): Result { contract { @@ -186,3 +188,25 @@ inline fun Result.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 Result.toErrorUnless(predicate: (V) -> Boolean, transform: (V) -> E): Result { + 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 + } +}