如何使用模式匹配捕获多个变量?

How can I capture multiple variables using pattern matching?

例如:

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

_* 可以 匹配 多个变量,但似乎能够 捕获 它们。

谢谢!

List(1, 2, 3, 4) match {
  case _ :: _ :: tail => println(tail) // prints List(3, 4)
}

您可以简单地通过 cons 运算符匹配列表:

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

您可以使用 rest @ _* 来做到这一点:

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

请注意,这是通用的:您可以使用 x @ pattern 将名称 x 赋予与 pattern 匹配的任何值(前提是该值具有合适的类型)。参见 http://scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#pattern-binders

另一种调用列表模式匹配的方法,

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

其中提取

x: Int = 1
y: Int = 2
rest: Seq[Int] = List(3, 4)