How to perform pattern matching with vararg case classes?

functional-programming, pattern-matching, scala

Solution

Either of these will work, the second is probably preferred if a little weird at first glance. See 8.1.9 Pattern Sequences from the Scala Reference.

case g: Group => g.shape.map(size(_)).sum

case Group(ss @ _*) => ss.map(size(_)).sum

This is using Scala 2.8. `sum` may not work on older versions.

Problem

I have a set of case classes like this ``` abstract class Shape case class Rectangle(width: Int, height: Int) extends Shape case class Location(x: Int, y: Int, shape: Shape) extends Shape case class Circle(radius: Int) extends Shape case class Group(shape: Shape*) extends Shape ``` where basically Group is an array of shapes. I need to define a size method for computing sizes for rectangle, circle and location its straightforward just return one. But i am having difficulty for Group. ``` object size extends Shape{ def size(s: Any) : Int = s match { case Rectangle(x,y) => 1 case Group // how to do it? Also having case Group(shape : Shape*) gives an error case Circle(r) => 1 case Location(x,y,shape) => 1 } } ``` I know for Group i need to use map and fold left, but i really cant create a logic for it. Thanks

Original source