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
A pattern match includes a sequence of alternatives, each starting with the keyword case. Each alternative includes a pattern and one or more expressions, which will be evaluated if the pattern matches. An arrow symbol => separates the pattern from the expressions.
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
Case classes help us use the power of inheritance to perform pattern matching. The case classes extend a common abstract class. The match expression then evaluates a reference of the abstract class against each pattern expressed by each case class.
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 SomeObject
s that define the MixedTypes
. You can treat is just like a sequence of whatever-the-constructor-args-for-MixedTypes-is.
Programming Scala by Wampler/Payne has an example.
Also some another SO question: Pattern matching a String as Seq[Char]
And the Daily Scala blog post on unapplySeq.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With