Created
March 26, 2012 15:04
-
-
Save nicktelford/2205715 to your computer and use it in GitHub Desktop.
Pattern matching - why is it implemented at the language level?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Any { | |
implicit def matching[A](a: A): Matchable[A] = new Matchable(a) | |
sealed class Matchable[A](o: A) { | |
// "match" is a reserved word, so lets call it "matchIt" instead | |
def matchIt[B](pf: PartialFunction[A, B]): B = { | |
if(pf.isDefinedAt(o)) { | |
pf(o) | |
} else { | |
throw new MatchError("...") | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment