All Downloads are FREE. Search and download functionalities are using the official Maven repository.

gnese.kotlin-result-ext.0.1.source-code.result.kt Maven / Gradle / Ivy

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 }
    }