Skip to content

Instantly share code, notes, and snippets.

@marenovakovic
Created October 30, 2025 16:00
Show Gist options
  • Save marenovakovic/c6df676fb3e671f23beeb1ba02509402 to your computer and use it in GitHub Desktop.
Save marenovakovic/c6df676fb3e671f23beeb1ba02509402 to your computer and use it in GitHub Desktop.
import kotlin.coroutines.cancellation.CancellationException
sealed class Result<out F, out S> {
data class Success<out S>(val value: S) : Result<Nothing, S>()
data class Failure<out F>(val failure: F) : Result<F, Nothing>()
inline fun <R> map(crossinline f: (S) -> R): Result<F, R> =
flatMap { Success(f(it)) }
inline fun <R> mapFailure(crossinline f: (F) -> R): Result<R, S> =
fold({ Failure(f(it)) }, { Success(it) })
inline fun <R> fold(crossinline ifFailure: (F) -> R, crossinline ifSuccess: (S) -> R): R =
when (this) {
is Success -> ifSuccess(value)
is Failure -> ifFailure(failure)
}
val isSuccess = this is Success
val isFailure = this is Failure
fun getOrNull(): S? = fold({ null }, { it })
fun exceptionOrNull(): F? = fold({ it }, { null })
companion object {
inline fun <R> catch(crossinline f: () -> R): Result<Throwable, R> =
try {
Success(f())
} catch (t: Throwable) {
if (t is CancellationException) throw t
else Failure(t)
}
inline fun <F> ensure(condition: Boolean, crossinline f: () -> F): Result<F, Unit> =
if (condition) Success(Unit)
else Failure(f())
}
}
inline fun <F, S, R> Result<F, S>.flatMap(crossinline f: (S) -> Result<F, R>): Result<F, R> =
when (this) {
is Result.Success -> f(this.value)
is Result.Failure -> this
}
fun <T> T.success() = Result.Success(this)
fun <T> T.failure() = Result.Failure(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment