andThen

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

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

  1. auto ref andThen(auto ref EX exp, auto ref VEX value)
  2. auto ref andThen(auto ref EX exp, Args args)
    @safe ref
    andThen
    (
    alias pred
    EX : Expected!(T, E, H)
    T
    E
    H
    Args...
    )
    (
    auto ref EX exp
    ,
    Args args
    )

Parameters

exp
Type: EX

The Expected to call andThen on

pred

The predicate to call if the there isn't an error

Examples

1 import std.format : format;
2 
3 assert(ok(42).andThen(ok(1)) == 1);
4 assert(ok(42).andThen!(() => ok(0)) == 0);
5 assert(ok(42).andThen(err!int("foo")).error == "foo");
6 assert(ok(42).andThen!(() => err!int("foo")).error == "foo");
7 assert(err!int("foo").andThen(ok(42)).error == "foo");
8 assert(err!int("foo").andThen!(() => ok(42)).error == "foo");
9 assert(err!int("foo").andThen(err!int("bar")).error == "foo");
10 assert(err!int("foo").andThen!(() => err!int("bar")).error == "foo");
11 
12 // with void value
13 assert(ok().andThen!(() => ok()));
14 assert(ok().andThen!(() => err("foo")).error == "foo");
15 assert(err("foo").andThen!(() => ok()).error == "foo");
16 
17 // with different value type
18 assert(ok(42).andThen(ok("foo")) == "foo");
19 assert(err!int("bug").andThen(ok("foo")).error == "bug");
20 assert(ok(42).andThen!(() => err!bool("foo")).error == "foo");
21 assert(err!int("bug").andThen!(() => err!bool("foo")).error == "bug");
22 
23 // with args
24 assert(ok(42).andThen!((v) => err!bool(v))("foo").error == "foo"); // doesn't use previous value
25 version (D_BetterC)
26     assert(ok(42).andThen!((i, v)
27         {
28             assert(i == 42);
29             assert(v == "foo");
30             return err!bool("betterc");
31         })("foo").error == "betterc"); // pass previous value to predicate
32 else
33     assert(ok(42).andThen!((i, v) => err!bool(format!"%s: %s"(v, i)))("foo").error == "foo: 42"); // pass previous value to predicate
34 assert(ok().andThen!((v) => ok(v))(42) == 42); // void type on first ok

Meta