[Issue 9959] New: Add functional pattern matching for object references
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Thu Apr 18 09:56:23 PDT 2013
http://d.puremagic.com/issues/show_bug.cgi?id=9959
Summary: Add functional pattern matching for object references
Product: D
Version: D2
Platform: All
OS/Version: All
Status: NEW
Keywords: pull
Severity: enhancement
Priority: P2
Component: Phobos
AssignedTo: nobody at puremagic.com
ReportedBy: GenericNPC at gmail.com
--- Comment #0 from IdanArye <GenericNPC at gmail.com> 2013-04-18 09:56:20 PDT ---
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.
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list