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(EX exp, VEX value)
  2. auto ref andThen(EX exp, Args args)
    ref
    andThen
    (
    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 andThen on

pred

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

Examples

import std.format : format;

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

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

// with different value type
assert(ok(42).andThen(ok("foo")) == "foo");
assert(err!int("bug").andThen(ok("foo")).error == "bug");
assert(ok(42).andThen!(() => err!bool("foo")).error == "foo");
assert(err!int("bug").andThen!(() => err!bool("foo")).error == "bug");

// with args
assert(ok(42).andThen!((v) => err!bool(v))("foo").error == "foo"); // doesn't use previous value
version (D_BetterC)
    assert(ok(42).andThen!((i, v)
        {
            assert(i == 42);
            assert(v == "foo");
            return err!bool("betterc");
        })("foo").error == "betterc"); // pass previous value to predicate
else
    assert(ok(42).andThen!((i, v) => err!bool(format!"%s: %s"(v, i)))("foo").error == "foo: 42"); // pass previous value to predicate
assert(ok().andThen!((v) => ok(v))(42) == 42); // void type on first ok

Meta