gnese.kotlin-result-ext.0.1.source-code.result.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-result-ext Show documentation
Show all versions of kotlin-result-ext Show documentation
Useful extensions to the stdlib Result monad and to all nullable types.
The newest version!
import kotlin.Result.Companion.failure
import kotlin.Result.Companion.success
fun Result.mapErr(block: (Throwable) -> Throwable): Result =
exceptionOrNull()?.let(block).let { maybeThrowable ->
if (maybeThrowable == null) {
this
} else {
failure(maybeThrowable)
}
}
fun Result.and(other: Result): Result =
if (isSuccess) {
other
} else {
this
}
fun Result.andThen(block: (T) -> Result): Result =
try {
block(getOrThrow())
} catch (e: Throwable) {
failure(e)
}
fun Result.or(other: Result): Result =
if (isSuccess) {
this
} else {
other
}
fun Result.orElse(block: (Throwable) -> Result): Result =
exceptionOrNull().map(block).let {
if (it == null) {
this
} else {
it
}
}
fun Result.transpose(): Result? =
try {
getOrThrow()?.let { success(it) }
} catch (_: Throwable) {
this.map { null }
}