Bug 9959 – Add functional pattern matching for object references
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-04-18T09:56:00Z
Last change time
2014-09-16T14:15:14Z
Keywords
pull
Assigned to
nobody
Creator
GenericNPC
Comments
Comment #0 by GenericNPC — 2013-04-18T09:56:20Z
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`:
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:
obj.castSwitch!(
(A a) => ...,
(B b) => ...,
)()
It answers both mentioned problems, plus it is more compact readable.