commonMain.fr.acinq.lightning.utils.Try.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of lightning-kmp Show documentation
Show all versions of lightning-kmp Show documentation
A Kotlin Multiplatform implementation of the Lightning Network
package fr.acinq.lightning.utils
sealed class Try {
abstract val isSuccess: Boolean
val isFailure: Boolean get() = !isSuccess
abstract fun get(): T
abstract fun getOrElse(f: () -> T): T
abstract fun recoverWith(f: () -> Try): Try
abstract fun map(f: (T) -> R): Try
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) }
}
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
}
companion object {
operator fun invoke(block: () -> T): Try = runTrying(block)
}
}
inline fun runTrying(block: () -> R): Try =
try {
Try.Success(block())
} catch (e: Throwable) {
Try.Failure(e)
}
inline fun T.runTrying(block: T.() -> R): Try =
try {
Try.Success(block())
} catch (e: Throwable) {
Try.Failure(e)
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy