D-Programming-Language/phobos — pull request #1266 by someboddy (2013-04-18 17:00:36+00:00)
Title: fix issue 9959 - Add functional pattern matching for object references

Polymorphism is usually the way to write code that handles objects of different
types, bit it is not always possible or desirable. When the code that uses the
objects is required to treat objects differently based on class, the D way is
using cast&assign inside `if`:
```D
if (auto a = cast(A) obj)
{
...
}
else if (auto b = cast(B) obj)
{
...
}
```
This is not always convenient for two reasons:

* You need to write `obj` in every `if` statement. If `obj` is a more complex
expression(like the return value of a function) you'll need to store it in an
variable beforehand. This is not that cumbersome but still worth mentioning.

* An `if` statement is a statement - which means it does not return a value -
and creates it's own scope - which means you variables declared in it are not
accessible outside. Those two constraints mean that if you need to compute a
value differently based on the object's class and use that value after the
`if`s, you need to declare the variable before the `if` - and that means you
can't make it `const`.

My solution is the function `std.algorithm.castSwitch`, which is based on
Scala's
approach(http://ofps.oreilly.com/titles/9780596155957/RoundingOutTheEssentials.html#MatchingOnType).
It is used like this:
```D
obj.castSwitch!(
(A a) => ...,
(B b) => ...,
)()
```
It answers both mentioned problems, plus it is more compact readable.

See http://d.puremagic.com/issues/show_bug.cgi?id=9959