1

I'm reviewing some Scala code trying to learn the language. Ran into a piece that looks like the following:

 case x if x startsWith "+" => 
          val s: Seq[Char] = x
          s match {
            case Seq('+', rest @ _*) => r.subscribe(rest.toString){ m => }
          }

In this case, what exactly is rest @ _* doing? I understand this is a pattern match for a Sequence, but I'm not exactly understanding what that second parameter in the Sequence is supposed to do.

Was asked for more context so I added the code block I found this in.

randombits
  • 47,058
  • 76
  • 251
  • 433

2 Answers2

5

If you have come across _* before in the form of applying a Seq as varargs to some method/constructor, eg:

val myList = List(args: _*)

then this is the "unapply" (more specifically, search for "unapplySeq") version of this: take the sequence and convert back to a "varargs", then assign the result to rest.

Shadowlands
  • 14,994
  • 4
  • 45
  • 43
2

x @ p matches the pattern p and binds the result of the whole match to x. This pattern matches a Seq containing '+' followed by any number (*) of unnamed elements (_) and binds rest to a Seq of those elements.

Jon Purdy
  • 53,300
  • 8
  • 96
  • 166
  • 1
    Is `*` the name of an extractor, or is it syntactic? – Owen Oct 04 '13 at 01:48
  • What would be great also is some terminology I can google to see more examples/explanations. I tried searching 'pattern matching', but it doesn't go into extractors or anything similar. – randombits Oct 04 '13 at 02:12
  • 1
    @randombits I tried googling for "scala pattern match unapplySeq" and came up with [this link](http://daily-scala.blogspot.com.au/2009/09/extract-sequences-unapplyseq.html) – Shadowlands Oct 04 '13 at 02:43
  • @Owen, it is syntactic feature related to varargs. – Vladimir Matveev Oct 04 '13 at 05:33