Scoop API

scoop:scoop.std:0.1.0

src/results/option.scoop

Selected production source · src/results/option.scoop

1package scoop
3/**
4 * Transforms Some and wraps the result, leaving None unchanged.
5 */
6public fun <T, R> Option<T>.map(transform: (T) -> R): R? =
7 when (this) {
8 case Some(val value) -> Some(transform(value))
9 case None -> None
10 }
12/**
13 * Transforms Some with an Option-producing callback, leaving None unchanged.
14 * See `scoop example language/option` for a chain that preserves absence.
15 */
16public fun <T, R> Option<T>.flatMap(transform: (T) -> R?): R? =
17 when (this) {
18 case Some(val value) -> transform(value)
19 case None -> None
20 }
22/**
23 * Keeps Some only if its value satisfies the predicate.
24 */
25public fun <T> Option<T>.filter(predicate: (T) -> Boolean): T? =
26 when (this) {
27 case Some(val value) -> if (predicate(value))
28 this
29 else
30 None
31 case None -> None
32 }
34/**
35 * Runs the Some callback for a present value or the onNone callback when absent.
36 */
37public fun <T, R> Option<T>.fold(onSome: (T) -> R, onNone: () -> R): R =
38 when (this) {
39 case Some(val value) -> onSome(value)
40 case None -> onNone()
41 }
43/**
44 * Returns a present value, evaluating the fallback only for None.
45 * See `scoop example language/option` and `scoop example test/assertions`
46 * for fallback values and callback evaluation checks.
47 */
48public fun <T> Option<T>.getOrElse(defaultValue: () -> T): T =
49 when (this) {
50 case Some(val value) -> value
51 case None -> defaultValue()
52 }
54/**
55 * Keeps Some, evaluating the alternative Option only for None.
56 * See `scoop example language/option` for alternatives that retain an empty present value.
57 */
58public fun <T> Option<T>.orElse(defaultValue: () -> T?): T? =
59 when (this) {
60 case Some(_) -> this
61 case None -> defaultValue()
62 }
64/**
65 * Maps Some to Success, producing a failure only for None.
66 */
67public fun <T, E> Option<T>.toResult(errorProducer: () -> E): Result<T, E> =
68 when (this) {
69 case Some(val value) -> Result.Success<T, E>(value)
70 case None -> Result.Failure<T, E>(errorProducer())
71 }