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)
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
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.
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 (eg, 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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.