views:

171

answers:

2

I have been searching for a bit but can not locate any examples that demonstrate the usage of @_* while pattern matching case classes.

Below is an example of the kind of application I am referring to.

def findPerimeter(o: SomeObject): Perimeter = o match {
case Type1(length, width) =>
  new Perimeter(0, 0, length, width)
case Type2(radius) =>
  new Perimeter(0, 0, 2*radius, 2*radius)
...

case MixedTypes(group @_*) => {
  \\How could @_* be used to check subpatterns of group?
}

}

If someone could show me some examples or point me to a web page that has a few examples that would be great.

Thanks

+3  A: 

Programming Scala by Wampler/Payne has an example.

Also some another SO question: http://stackoverflow.com/questions/740563/pattern-matching-a-string-as-seqchar

And the Daily Scala blog post on unapplySeq.

huynhjl
+3  A: 

Remember that something like

Type2(3.0) match {
  case t2 @ Type2(radius) => //...
}

binds radius to the value 3.0 and binds t2 to the instance of Type2 being matched against.

Using your example:

def findPerimeter(o: SomeObject): Perimeter = o match {
  case Type1(length, width) => new Perimeter(0, 0, length, width)
  case Type2(radius) => new Perimeter(0, 0, 2*radius, 2*radius)
  // ...
  // assume that Perimeter defines a + operator
  case MixedTypes(group @ _*) => group.reduceLeft(findPerimeter(_) + findPerimeter(_))

}

Here, group is bound to the sequence of SomeObjects that define the MixedTypes. You can treat is just like a sequence of whatever-the-constructor-args-for-MixedTypes-is.

Mitch Blevins