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

commonMain.progressive.Accessors.kt Maven / Gradle / Ivy

The newest version!
package opensavvy.state.progressive

import opensavvy.progress.Progress
import opensavvy.state.ExperimentalProgressiveRaiseApi
import opensavvy.state.outcome.Outcome
import opensavvy.state.progressive.ProgressiveOutcome.*

// region Get or null

/**
 * Returns [Success.value], or `null` if this outcome is not successful.
 */
val  ProgressiveOutcome<*, Value>.valueOrNull: Value?
	get() = (this as? Success)?.value

/**
 * Returns [Failure.failure][ProgressiveOutcome.Failure.failure], or `null` if this outcome is not a failure.
 */
val  ProgressiveOutcome.failureOrNull: Failure?
	get() = (this as? ProgressiveOutcome.Failure)?.failure

// endregion
// region Safe get via Nothing

/**
 * Returns [Success.value].
 */
val  ProgressiveOutcome.value: Value
	// This cast is safe, because a Success of Nothing is impossible
	get() = (this as Success).value

/**
 * Returns [Failure.failure][ProgressiveOutcome.Failure.failure].
 */
val  ProgressiveOutcome.failure: Failure
	// This cast is safe, because a Success of Nothing is impossible
	get() = (this as ProgressiveOutcome.Failure).failure

/**
 * The progression of this unsuccessful value.
 *
 * See [ProgressiveOutcome].
 */
@ExperimentalProgressiveRaiseApi
val  Unsuccessful.progress: Progress
	get() = when (this) {
		is ProgressiveOutcome.Failure -> progress
		is Incomplete -> progress
	}

// endregion
// region Conversion

/**
 * Converts this progressive outcome into a [regular outcome][Outcome].
 *
 * Because regular outcomes do not have a concept of progression, the progress information is lost.
 * To access both the outcome and the progression information, consider using destructuration instead:
 * ```kotlin
 * val (outcome, progression) = /* ProgressiveOutcome */
 * ```
 */
fun  ProgressiveOutcome.asOutcome() = when (this) {
	is Success -> Outcome.Success(value)
	is ProgressiveOutcome.Failure -> Outcome.Failure(failure)
	is Incomplete -> null
}

//endregion
//region Destructuration

/**
 * Syntax sugar for [asOutcome].
 */
operator fun  ProgressiveOutcome.component1() = asOutcome()

/**
 * Syntax sugar for [ProgressiveOutcome.progress].
 */
operator fun ProgressiveOutcome<*, *>.component2() = progress

//endregion




© 2015 - 2024 Weber Informatics LLC | Privacy Policy