Skip to content

Commit

Permalink
Add .toResult and .mapFailure Result extensions (#81)
Browse files Browse the repository at this point in the history
* Add .toResult and .mapFailure Result extensions
  • Loading branch information
ametke authored May 21, 2024
1 parent c85d1bf commit e3342f6
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/api/lib.api
Original file line number Diff line number Diff line change
Expand Up @@ -272,8 +272,10 @@ public final class app/cash/quiver/extensions/OptionKt {

public final class app/cash/quiver/extensions/ResultKt {
public static final fun failure (Ljava/lang/Throwable;)Ljava/lang/Object;
public static final fun mapFailure (Ljava/lang/Object;Lkotlin/jvm/functions/Function1;)Ljava/lang/Object;
public static final fun success (Ljava/lang/Object;)Ljava/lang/Object;
public static final fun toEither (Ljava/lang/Object;)Larrow/core/Either;
public static final fun toResult (Ljava/lang/Object;Lkotlin/jvm/functions/Function0;)Ljava/lang/Object;
}

public final class app/cash/quiver/extensions/SequenceKt {
Expand Down
19 changes: 19 additions & 0 deletions lib/src/main/kotlin/app/cash/quiver/extensions/Result.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,22 @@ fun <T> T.success(): Result<T> = Result.success(this)
* Make any exception a Failure.
*/
fun <T : Throwable> T.failure(): Result<T> = Result.failure(this)


/**
* Turns a nullable value into a [Result].
*/
inline fun <A : Throwable, B> B?.toResult(error: () -> A): Result<B> =
this?.let { Result.success(it) } ?: Result.failure(error())

/**
* If a [Result] is a failure, maps the underlying [Throwable] to a new [Throwable].
*/
inline fun <N : Throwable, T> Result<T>.mapFailure(
f: (exception: Throwable) -> N
): Result<T> {
return when (val exception = exceptionOrNull()) {
null -> Result.success(getOrThrow())
else -> Result.failure(f(exception))
}
}
11 changes: 11 additions & 0 deletions lib/src/test/kotlin/app/cash/quiver/extensions/ResultTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,15 @@ class ResultTest : StringSpec({
it.failure() shouldBeFailure it
}
}

"toResult converts nullable values into Result" {
null.toResult { RuntimeException("boo!") }.shouldBeFailure()
0.toResult { RuntimeException("boo!") } shouldBeSuccess 0
}

"mapLeft maps the failure of a Result" {
val finalException = RuntimeException("Unable to map invalid integer")
Result.failure<Int>(NumberFormatException("Invalid integer")).mapFailure { finalException } shouldBeFailure
finalException
}
})

0 comments on commit e3342f6

Please sign in to comment.