As other posters have pointed out, List(x)
only matches a list of 1 element.
There is however syntax for matching multiple elements:
def example(list: List[Int]) = list match {
case Nil => println("Nil")
case List(x @ _*) => println(x)
}
example(List(11, 3, -5, 5, 889, 955, 1024)) // Prints List(11, 3, -5, 5, 889, 955, 1024)
It's the funny @ _*
thing that makes the difference. _*
matches a repeated parameter, and x @
says "bind this to x
".
The same works with any pattern match that can match repeated elements (e.g, Array(x @ _*)
or Seq(x @ _*)
). List(x @ _*)
can also match empty lists, although in this case, we've already matched Nil.
You can also use _*
to match "the rest", as in:
def example(list: List[Int]) = list match {
case Nil => println("Nil")
case List(x) => println(x)
case List(x, xs @ _*) => println(x + " and then " + xs)
}