Expected

An Expected!(T, E) contains either an expected value of type T, or an error value of type E explaining why the expected value couldn't be produced.

The default type for the error value is Exception.

A function that returns an Expected object has the following advantages over one that may throw an exception or return an error code:

  • It leaves the choice between manual error checking and automatic stack unwinding up to the caller.
  • It allows error handling to be deferred until the return value is actually needed (if ever).
  • It can be easily composed with other functions using map and flatMap, which propagates error values automatically.
  • It can be used in nothrow code.

An Expected!(T, E) is initialized by default to contain the value T.init.

Unlike a thrown exception, an error returned via an Expected object will be silently ignored if the function's return value is discarded. For best results, functions that return Expected objects should be marked as pure, so that the D compiler will warn about discarded return values.

Constructors

this
this(T value)

Constructs an Expected object that contains an expected value.

this
this(E err)

Constructs an Expected object that contains an error value.

Members

Functions

error
inout(E) error()

Returns the error value. May only be called when hasValue returns false.

hasValue
bool hasValue()

Checks whether this Expected object contains an expected value or an error value.

opAssign
void opAssign(T value)

Assigns an expected value to an Expected object.

opAssign
void opAssign(E err)

Assigns an error value to an Expected object.

opEquals
bool opEquals(T rhs)

Checks whether this Expected object contains a specific expected value.

opEquals
bool opEquals(E rhs)

Checks whether this Expected object contains a specific error value.

opEquals
bool opEquals(Expected!(T, E) rhs)

Checks whether this Expected object and rhs contain the same expected value or error value.

value
inout(T) value()

Returns the expected value if there is one. Otherwise, throws an exception

valueOr
inout(T) valueOr(inout(T) defaultValue)

Returns the expected value if present, or a default value otherwise.

Meta