I’m teaching myself Scala and I have sort of a philosophical question. Is pattern matching a language feature of Scala, or just a library feature? To put it another way, could I, were I sufficiently skilled, write xmatch, a function that was identical to match in every way except the name? Actually, I think those are two slightly different questions: is matching a library feature, and could it be a library feature?
I was thinking of trying to re-write match, purely as an exercise, but I wanted some assurance it was possible.
Pattern matching is a language feature, of which the
matchstatement is only the most notable example. Here are two other commonly-used examples:So, no, you can’t do that on your own. The language does not allow you to define new ways to create variables, so these things can only happen with language support.
The
matchstatement itself uses the pattern-matching variable-creation support inside the language, but otherwise could in principle be implemented as a library feature. However, it would be inefficient in several cases:So, all in all, no, you can’t write pattern matching yourself, and while you could write the match statement, there are advantages in using the existing one.