orElse

Returns the value contained within the Expected _or else_ another value if there's an error. This function can be used for control flow based on Expected values.

Predicate can accept no arguments, variable arguments, or previous result error value with additional variable arguments. It must return Expected wth the same value type. But can provide different error value type.

  1. U orElse(auto ref EX exp, lazy U value)
    @safe ref
    U
    orElse
    (
    EX
    U
    )
    (
    auto ref EX exp
    ,
    lazy U value
    )
    if (
    is(EX : Expected!(T, E, H),
    T
    E
    H
    ) &&
    is(U : T)
    )
  2. auto ref orElse(auto ref EX exp, Args args)

Parameters

exp
Type: EX

The Expected to call orElse on

value
Type: U

The value to return if there is an error

Examples

1 assert(ok(42).orElse(0) == 42);
2 assert(ok(42).orElse!(() => 0) == 42);
3 assert(err!int("foo").orElse(0) == 0);
4 assert(err!int("foo").orElse!(() => 0) == 0);
5 assert(ok(42).orElse!(() => ok(0)) == 42);
6 assert(err!int("foo").orElse!(() => ok(42)) == 42);
7 assert(err!int("foo").orElse!(() => err!int("bar")).error == "bar");
8 
9 // with void value
10 assert(ok().orElse!(() => err("foo")));
11 assert(err("foo").orElse!(() => ok()));
12 assert(err("foo").orElse!(() => err("bar")).error == "bar");
13 
14 // with args
15 assert(err!int("foo").orElse!((v) => v)(42) == 42);
16 
17 // with different error type
18 assert(err!int("foo").orElse!((v) => ok!int(v))(42).value == 42); // string -> int
19 assert(err!int("foo").orElse!((v) => err!int(v))(42).error == 42);
20 assert(err!int("foo").orElse!((e, v) => err!int(e.length + v))(42).error == 45); // with previous error

Meta