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.

castSwitch
(
choices...
)
()

Parameters

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 Object

the object against which the tests are being made.

Return Value

Type: auto

The value of the selected choice.

Note: castSwitch can only be used with object types.

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.

Examples

1 import std.algorithm.iteration : map;
2 import std.format : format;
3 
4 class A
5 {
6     int a;
7     this(int a) {this.a = a;}
8     @property int i() { return a; }
9 }
10 interface I { }
11 class B : I { }
12 
13 Object[] arr = [new A(1), new B(), null];
14 
15 auto results = arr.map!(castSwitch!(
16                             (A a) => "A with a value of %d".format(a.a),
17                             (I i) => "derived from I",
18                             ()    => "null reference",
19                         ))();
20 
21 // A is handled directly:
22 assert(results[0] == "A with a value of 1");
23 // B has no handler - it is handled by the handler of I:
24 assert(results[1] == "derived from I");
25 // null is handled by the null handler:
26 assert(results[2] == "null reference");

Using with void handlers:

1 import std.exception : assertThrown;
2 
3 class A { }
4 class B { }
5 // Void handlers are allowed if they throw:
6 assertThrown!Exception(
7     new B().castSwitch!(
8         (A a) => 1,
9         (B d)    { throw new Exception("B is not allowed!"); }
10     )()
11 );
12 
13 // Void handlers are also allowed if all the handlers are void:
14 new A().castSwitch!(
15     (A a) { },
16     (B b) { assert(false); },
17 )();

Meta

Suggestion Box / Bug Report