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

commonMain.fr.acinq.bitcoin.utils.Try.kt Maven / Gradle / Ivy

package fr.acinq.bitcoin.utils

public sealed class Try {
    public abstract val isSuccess: Boolean
    public val isFailure: Boolean get() = !isSuccess
    public abstract fun get(): T
    public abstract fun getOrElse(f: () -> T): T
    public abstract fun recoverWith(f: () -> Try): Try
    public abstract fun  map(f: (T) -> R): Try

    public data class Success(val result: T) : Try() {
        override val isSuccess: Boolean = true
        override fun get(): T = result
        override fun getOrElse(f: () -> T): T = result
        override fun recoverWith(f: () -> Try): Try = this
        override fun  map(f: (T) -> R): Try = runTrying { f(result) }
    }

    public data class Failure(val error: Throwable) : Try() {
        override val isSuccess: Boolean = false
        override fun get(): T = throw error
        override fun getOrElse(f: () -> T): T = f()
        override fun recoverWith(f: () -> Try): Try = f()

        @Suppress("UNCHECKED_CAST")
        override fun  map(f: (T) -> R): Try = this as Try
    }

    public companion object {
        public operator fun  invoke(block: () -> T): Try = runTrying(block)
    }
}

public inline fun  runTrying(block: () -> R): Try =
    try {
        Try.Success(block())
    } catch (e: Throwable) {
        Try.Failure(e)
    }

public inline fun  T.runTrying(block: T.() -> R): Try =
    try {
        Try.Success(block())
    } catch (e: Throwable) {
        Try.Failure(e)
    }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy