-
Notifications
You must be signed in to change notification settings - Fork 55
/
Or.kt
57 lines (49 loc) · 1.54 KB
/
Or.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.github.michaelbull.result
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@Deprecated("Use lazy-evaluating variant instead", ReplaceWith("or { result }"))
infix fun <V, E> Result<V, E>.or(result: Result<V, E>): Result<V, E> {
return or { result }
}
/**
* Returns [result] if this [Result] is [Err], otherwise this [Ok].
*
* - Rust: [Result.or](https://doc.rust-lang.org/std/result/enum.Result.html#method.or)
*/
inline infix fun <V, E> Result<V, E>.or(result: () -> Result<V, E>): Result<V, E> {
contract {
callsInPlace(result, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Ok -> this
is Err -> result()
}
}
/**
* Returns the [transformation][transform] of the [error][Err.error] if this [Result] is [Err],
* otherwise this [Ok].
*
* - Rust: [Result.or_else](https://doc.rust-lang.org/std/result/enum.Result.html#method.or_else)
*/
inline infix fun <V, E> Result<V, E>.orElse(transform: (E) -> Result<V, E>): Result<V, E> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Ok -> this
is Err -> transform(error)
}
}
/**
* Returns the [transformation][transform] of the [error][Err.error] if this [Result] is [Err],
* otherwise this [Ok].
*/
inline infix fun <V, E> Result<V, E>.recover(transform: (E) -> V): Ok<V> {
contract {
callsInPlace(transform, InvocationKind.AT_MOST_ONCE)
}
return when (this) {
is Ok -> this
is Err -> Ok(transform(error))
}
}