Last active
August 29, 2015 14:26
-
-
Save marcel/2927db8e3f6f9b746d4f to your computer and use it in GitHub Desktop.
unapply tuple extraction
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
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