Reputation:
I wonder, why doesn't this work:
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))
It says:
scala.MatchError: List(11, 3, -5, 5, 889, 955, 1024) (of class scala.collection.immutable.$colon$colon)
Upvotes: 4
Views: 2175
Reputation: 3307
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)
}
Upvotes: 3
Reputation: 3441
It doesn't work because List(x)
means a list with exactly one element. Check it:
def example(list: List[Int]) = list match {
case Nil => println("Nil")
case List(x) => println("one element: " + x)
case xs => println("more elements: " + xs)
}
example(List(11, 3, -5, 5, 889, 955, 1024))
//more elements: List(11, 3, -5, 5, 889, 955, 1024)
example(List(5))
//one element: 5
Upvotes: 14
Reputation: 170733
Because List(x)
only matches lists with one element. So
def example(list: List[Int]) = list match {
case Nil => println("Nil")
case List(x) => println(x)
}
only works with lists of zero or one element.
Upvotes: 5