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(EX exp, U value)
  2. auto ref orElse(EX exp, Args args)
    ref
    orElse
    (
    alias pred
    EX : Expected!(T, E, H)
    T
    E
    H
    Args...
    )
    (
    auto ref EX exp
    ,
    auto ref Args args
    )

Parameters

exp EX

The Expected to call orElse on

pred

The predicate to call if the there is an error

Examples

assert(ok(42).orElse(0) == 42);
assert(ok(42).orElse!(() => 0) == 42);
assert(err!int("foo").orElse(0) == 0);
assert(err!int("foo").orElse!(() => 0) == 0);
assert(ok(42).orElse!(() => ok(0)) == 42);
assert(err!int("foo").orElse!(() => ok(42)) == 42);
assert(err!int("foo").orElse!(() => err!int("bar")).error == "bar");

// with void value
assert(ok().orElse!(() => err("foo")));
assert(err("foo").orElse!(() => ok()));
assert(err("foo").orElse!(() => err("bar")).error == "bar");

// with args
assert(err!int("foo").orElse!((v) => v)(42) == 42);

// with different error type
assert(err!int("foo").orElse!((v) => ok!int(v))(42).value == 42); // string -> int
assert(err!int("foo").orElse!((v) => err!int(v))(42).error == 42);
assert(err!int("foo").orElse!((e, v) => err!int(e.length + v))(42).error == 45); // with previous error

Meta