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)
因为List(x)只匹配具有一个元素的列表.所以
def example(list: List[Int]) = list match {
case Nil => println("Nil")
case List(x) => println(x)
}
Run Code Online (Sandbox Code Playgroud)
仅适用于零个或一个元素的列表.