diff --git a/CHANGELOG.md b/CHANGELOG.md index 7267d60..da8424a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Added * Adds `Result.unit(): Result` as alias for `.map { }` (Jem Mawson) * Adds `Result.tap` and `Result.flatTap` (Jem Mawson) +* Adds `Result.toOutcome` (Jem Mawson) ## [0.5.5] - 2024-06-20 diff --git a/lib/api/lib.api b/lib/api/lib.api index bd9ba97..6b7d161 100644 --- a/lib/api/lib.api +++ b/lib/api/lib.api @@ -60,6 +60,7 @@ public final class app/cash/quiver/OutcomeKt { public static final fun tapFailure (Lapp/cash/quiver/Outcome;Lkotlin/jvm/functions/Function1;)Lapp/cash/quiver/Outcome; public static final fun toOutcome (Larrow/core/Either;)Lapp/cash/quiver/Outcome; public static final fun toOutcome (Larrow/core/Option;)Lapp/cash/quiver/Outcome; + public static final fun toOutcome (Ljava/lang/Object;)Lapp/cash/quiver/Outcome; public static final fun traverse (Lapp/cash/quiver/Outcome;Lkotlin/jvm/functions/Function1;)Larrow/core/Either; public static final fun traverse (Lapp/cash/quiver/Outcome;Lkotlin/jvm/functions/Function1;)Larrow/core/Option; public static final fun traverse (Lapp/cash/quiver/Outcome;Lkotlin/jvm/functions/Function1;)Larrow/core/Validated; diff --git a/lib/src/main/kotlin/app/cash/quiver/Outcome.kt b/lib/src/main/kotlin/app/cash/quiver/Outcome.kt index ca39c68..5d3d551 100644 --- a/lib/src/main/kotlin/app/cash/quiver/Outcome.kt +++ b/lib/src/main/kotlin/app/cash/quiver/Outcome.kt @@ -217,6 +217,11 @@ fun Either>.toOutcome(): Outcome = when (this) { fun Either.asOutcome(): Outcome = this.map(::Some).toOutcome() +fun Result.toOutcome(): Outcome = fold( + onSuccess = { Present(it) }, + onFailure = { Failure(it) } +) + fun Option.toOutcome(): Outcome = this.right().toOutcome() inline fun Outcome.orThrow(onAbsent: () -> Throwable): A = when (this) { diff --git a/lib/src/test/kotlin/app/cash/quiver/OutcomeTest.kt b/lib/src/test/kotlin/app/cash/quiver/OutcomeTest.kt index 8ba1151..74c32a9 100644 --- a/lib/src/test/kotlin/app/cash/quiver/OutcomeTest.kt +++ b/lib/src/test/kotlin/app/cash/quiver/OutcomeTest.kt @@ -17,6 +17,7 @@ import arrow.core.right import arrow.core.some import arrow.core.valid import app.cash.quiver.continuations.outcome +import app.cash.quiver.extensions.success import io.kotest.assertions.arrow.core.shouldBeInvalid import io.kotest.assertions.arrow.core.shouldBeLeft import io.kotest.assertions.arrow.core.shouldBeNone @@ -190,6 +191,12 @@ class OutcomeTest : StringSpec({ }.shouldBeAbsent() } + "Lift Result into Outcome" { + val e = RuntimeException("hey") + Result.success(1).toOutcome().shouldBePresent().shouldBe(1) + Result.failure(e).toOutcome().shouldBeFailure().shouldBe(e) + } + "Lift Either into Outcome" { 1.right().asOutcome().shouldBePresent().shouldBe(1) "bad".left().asOutcome().shouldBeFailure().shouldBe("bad")