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

arrow.generic.coproduct2.Coproduct2.kt Maven / Gradle / Ivy

package arrow.generic.coproduct2

import arrow.core.Option
import arrow.core.toOption
import kotlin.Suppress
import kotlin.Unit

/**
 * Represents a sealed hierarchy of 2 types where only one of the types is actually present.
 */
sealed class Coproduct2

/**
 * Represents the first type of a Coproduct2
 */
data class First(val a: A) : Coproduct2()

/**
 * Represents the second type of a Coproduct2
 */
data class Second(val b: B) : Coproduct2()

/**
 * Creates a Coproduct from the A type
 *
 * @return A Coproduct2 where the receiver is the A
 */
fun  A.first(): Coproduct2 = First(this)

/**
 * Creates a Coproduct from the B type
 *
 * @return A Coproduct2 where the receiver is the B
 */
fun  B.second(): Coproduct2 = Second(this)

/**
 * Transforms the Coproduct into an Option based on the actual value of the Coproduct
 *
 * @return None if the Coproduct was not the specified type, Some if it was the specified type
 */
fun  Coproduct2.select(): Option = (this as? First)?.a.toOption()

/**
 * Transforms the Coproduct into an Option based on the actual value of the Coproduct
 *
 * @return None if the Coproduct was not the specified type, Some if it was the specified type
 */
@Suppress("UNUSED_PARAMETER")
fun  Coproduct2<*, B>.select(dummy0: Unit = Unit): Option = (this as? Second)?.b.toOption()

/**
 * Runs the function related to the actual value of the Coproduct and returns the result
 *
 * @param a The function used to map A to the RESULT type
 * @param b The function used to map B to the RESULT type
 *
 * @return RESULT generated by one of the input functions
 */
fun  Coproduct2.fold(a: (A) -> RESULT, b: (B) -> RESULT): RESULT = when (this) {
    is First -> a(this.a)
    is Second -> b(this.b)
}