View source code Display the source code in std/algorithm/comparison.d from which this page was generated on github. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

Function std.algorithm.comparison.castSwitch

Executes and returns one of a collection of handlers based on the type of the switch object.

The first choice that switchObject can be casted to the type of argument it accepts will be called with switchObject casted to that type, and the value it'll return will be returned by castSwitch.

If a choice's return type is void, the choice must throw an exception, unless all the choices are void. In that case, castSwitch itself will return void.

Prototype

auto castSwitch(choices...)(
  Object switchObject
);

Throws

If none of the choice matches, a SwitchError will be thrown. SwitchError will also be thrown if not all the choices are void and a void choice was executed without throwing anything.

Parameters

NameDescription
choices The choices needs to be composed of function or delegate handlers that accept one argument. There can also be a choice that accepts zero arguments. That choice will be invoked if the switchObject is null.
switchObject the object against which the tests are being made.

Returns

The value of the selected choice.

Note

castSwitch can only be used with object types.

Example

import std.algorithm.iteration : map;
import std.format : format;

class A
{
    int a;
    this(int a) {this.a = a;}
    @property int i() { return a; }
}
interface I { }
class B : I { }

Object[] arr = [new A(1), new B(), null];

auto results = arr.map!(castSwitch!(
                            (A a) => "A with a value of %d".format(a.a),
                            (I i) => "derived from I",
                            ()    => "null reference",
                        ))();

// A is handled directly:
assert(results[0] == "A with a value of 1");
// B has no handler - it is handled by the handler of I:
assert(results[1] == "derived from I");
// null is handled by the null handler:
assert(results[2] == "null reference");

Example

Using with void handlers:

import std.exception : assertThrown;

class A { }
class B { }
// Void handlers are allowed if they throw:
assertThrown!Exception(
    new B().castSwitch!(
        (A a) => 1,
        (B d)    { throw new Exception("B is not allowed!"); }
    )()
);

// Void handlers are also allowed if all the handlers are void:
new A().castSwitch!(
    (A a) { assert(true); },
    (B b) { assert(false); },
)();

Authors

Andrei Alexandrescu

License

Boost License 1.0.

Comments