0

For example:

List(1,2,3,4) match {
  case List(x: Int, y: Int, *rest) =>
    println(rest) // i want to get List(3,4)
}

_* can match multiple variables but do to seem to be able to capture them.

Thanks!

elm
  • 20,117
  • 14
  • 67
  • 113
Chi Zhang
  • 771
  • 2
  • 8
  • 22

4 Answers4

4

You can use rest @ _* for this:

List(1,2,3,4) match {
  case List(x: Int, y: Int, rest @ _*) =>
    println(rest) 
}

Note that this is general: you can use x @ pattern to give the name x to any value matched by pattern (provided this value has a suitable type). See http://scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#pattern-binders.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
2
List(1, 2, 3, 4) match {
  case _ :: _ :: tail => println(tail) // prints List(3, 4)
}
Paweł Jurczenko
  • 4,431
  • 2
  • 20
  • 24
2

You can simply match lists by cons operator:

List(1, 2, 3, 4) match { 
    case x :: y :: rest => println(rest) 
} // gives you "List(3, 4)" to stdout
Fellrond
  • 211
  • 1
  • 7
1

Another way to invoke pattern matching on lists,

val List(x,y,rest @ _*) = List(1,2,3,4)

which extracts

x: Int = 1
y: Int = 2
rest: Seq[Int] = List(3, 4)
elm
  • 20,117
  • 14
  • 67
  • 113