http://stackoverflow.com/questions/2261358/pattern-matching-with-conjunctions-patterna-and-patternb.
As mentioned in an earlier post Matching with Or case expressions suppose 'or' expression combination using the '|' character. However 'and' combinations are not possible.
One solution is to build an && extractor object as follows:
- scala> case object && { def unapply[A](a: A) = Some((a, a))}
- defined module $amp$amp
- scala> object StartsWith { def unapply(s: String) = s.headOption}
- defined module StartsWith
- scala> object EndsWith { def unapply(s: String) = s.reverse.headOption}
- defined module EndsWith
- scala> "foo" match { case StartsWith('f') && EndsWith('o') => println("f*o") }
- f*o
Note: this is a scala 2.7 solution Scala 2.8 can be used to improve the EndsWith extractor by using the method lastOption instead of s.reverse.headOption.
No comments:
Post a Comment