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

fuookami.ospf.kotlin.utils.functional.Result.kt Maven / Gradle / Ivy

There is a newer version: 1.0.29
Show newest version
package fuookami.ospf.kotlin.utils.functional

import fuookami.ospf.kotlin.utils.error.*

sealed class Result {
    open val ok = false
    open val failed = false
    open val value: T? = null

    abstract fun  map(transform: (T) -> U): Result

    inline fun ifOk(crossinline func: Ok.() -> Unit): Result {
        when (this) {
            is Ok -> {
                func(this)
            }

            is Failed -> {}
        }
        return this
    }

    inline fun ifFailed(crossinline func: Failed.() -> Unit): Result {
        when (this) {
            is Ok -> {}

            is Failed -> {
                func(this)
            }
        }
        return this
    }
}

class Ok(
    override val value: T
) : Result() {
    override val ok = true

    inline fun  getAs(): U? {
        return if (value is U) {
            value
        } else {
            null
        }
    }

    override fun  map(transform: Extractor): Result {
        return Ok(transform(value))
    }
}

class Failed(
    val error: E
) : Result() {
    companion object {
        operator fun  invoke(code: ErrorCode, message: String? = null): Failed {
            return Failed(Err(code, message))
        }

        operator fun  invoke(code: ErrorCode, value: E): Failed {
            return Failed(ExErr(code, value))
        }

        operator fun  invoke(code: ErrorCode, message: String, value: E): Failed {
            return Failed(ExErr(code, message, value))
        }
    }

    override val failed = true

    val code by error::code
    val message by error::message

    val withValue by error::withValue
    val errValue by error::value

    override fun  map(transform: (T) -> U): Result {
        return Failed(error)
    }
}

class Success

val success = Success()

typealias Try = Result
typealias TryWith = Result
typealias Ret = Result

val ok = Ok(success)
fun  ok(): Result = Ok(success)