Outcome

sealed interface Outcome<out T>

Represents the result of an operation that can either succeed with a value or fail with an error.

This sealed interface provides a robust way to handle operations that may produce a value or an error, offering a type-safe alternative to exceptions or nullable types. It includes utility functions for mapping, recovering, and folding outcomes, as well as converting to and from Result.

Parameters

T

The type of the value in a successful outcome.

See also

Inheritors

Types

Link copied to clipboard
data class Failure(val message: String, val throwable: Throwable? = null, val outcome: Outcome<*>? = null) : Outcome<Nothing>

Represents a failed outcome with an error message and optional cause.

Link copied to clipboard
value class Success<T>(val value: T) : Outcome<T>

Represents a successful outcome with a value.

Properties

Link copied to clipboard
open val failed: Boolean

Indicates whether the operation failed (opposite of succeeded).

Link copied to clipboard
abstract val succeeded: Boolean

Indicates whether the operation succeeded.

Functions

Link copied to clipboard

Returns the Throwable of a Failure or null if the outcome is a Success.

Link copied to clipboard
inline suspend fun <T, R> Outcome<T>.flatMap(transform: suspend (T) -> Outcome<R>): Outcome<R>

Flat-maps the value of a successful Outcome using the provided transform function.

Link copied to clipboard
inline suspend fun <T, R> Outcome<T>.fold(onSuccess: suspend (T) -> R, onFailure: suspend (String, Throwable?) -> R): R

Folds the Outcome into a single value by applying onSuccess for a Success or onFailure for a Failure.

Link copied to clipboard
open fun getOrNull(): T?

Returns the value of a Success or null if the outcome is a Failure.

Link copied to clipboard
inline suspend fun <T, R> Outcome<T>.map(transform: suspend (T) -> R): Outcome<R>

Maps the value of a successful Outcome using the provided transform function.

Link copied to clipboard
inline suspend fun <T, R> Outcome<T>.mapCatching(transform: suspend (T) -> R): Outcome<R>

Maps the value of a successful Outcome using the provided transform function, catching any exceptions.

Link copied to clipboard
inline suspend fun <T> Outcome<T>.mapFailure(transform: suspend (Outcome.Failure) -> Outcome.Failure): Outcome<T>

Maps a Failure using the provided transform function, leaving Success unchanged.

Link copied to clipboard
inline suspend fun <T> Outcome<T>.recover(recoverBlock: suspend (Outcome.Failure) -> T): Outcome<T>

Recovers from a Failure by applying the recoverBlock function to produce a new value.

Link copied to clipboard
inline suspend fun <T> Outcome<T>.recoverCatching(recoverBlock: suspend (Outcome.Failure) -> T): Outcome<T>

Recovers from a Failure by applying the recoverBlock function, catching any exceptions.

Link copied to clipboard
open fun toResult(): Result<T>

Converts this Outcome to a Result.