Skip to content

Instantly share code, notes, and snippets.

@marcel
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcel/2927db8e3f6f9b746d4f to your computer and use it in GitHub Desktop.
Save marcel/2927db8e3f6f9b746d4f to your computer and use it in GitHub Desktop.
unapply tuple extraction
import scala.util.matching.Regex
import scala.util.matching.Regex.Match
trait RegexExtractor[M] {
def pattner: Regex
def unapply(line: String): Option[M] = {
pattern.findFirstMatchIn(line) map { matches =>
extractMatches(matches)
}
}
def extractMatches(matchData: Match): M
}
object OverridingExtractor extends RegexExtractor[(String, Int)] {
val pattern = "([a-z]+): ([0-9]+)".r
override def unapply(line: String) = {
pattern.findFirstMatchIn(line) map { matches =>
(matches.group(1), matches.group(2).toInt)
}
}
override def extractMatches(matchData: Match) = {
(matchData.group(1), matchData.group(2).toInt)
}
}
object MethodCallingExtractor extends RegexExtractor[(String, Int)] {
val pattern = "([a-z]+): ([0-9]+)".r
override def extractMatches(matchData: Match) = {
(matchData.group(1), matchData.group(2).toInt)
}
}
"age: 33" match {
case OverridingExtractor(label, age) =>
// label = "age", age = 33
case MethodCallingExtractor(label, age) =>
// label = ("age", 33), age = <no type infered> compiler error MethodCallingExtractor.type does not take parameters
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment