模式匹配不起作用

4 scala

我想知道,为什么这不起作用:

  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))
Run Code Online (Sandbox Code Playgroud)

它说:

scala.MatchError: List(11, 3, -5, 5, 889, 955, 1024) (of class scala.collection.immutable.$colon$colon)
Run Code Online (Sandbox Code Playgroud)

Inf*_*ity 14

它不起作用,因为它List(x)表示只包含一个元素的列表.核实:

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
Run Code Online (Sandbox Code Playgroud)

  • 这是scala中的常见问题,有用的链接:http://stackoverflow.com/questions/12218641/scala-2-10-what-is-a-typetag-and-how-do-i-use-it (2认同)

Ale*_*nov 5

因为List(x)只匹配具有一个元素的列表.所以

def example(list: List[Int]) = list match {
  case Nil => println("Nil")
  case List(x) => println(x)
}
Run Code Online (Sandbox Code Playgroud)

仅适用于零个或一个元素的列表.