检查集合中元素的准确数量
def f(ints: Seq[Int]): String = ints match { case Seq() => "Seq是空的!" case Seq(first) => s"The seq has exactly one element : $first" case Seq(first, second) => s"The seq has exactly two elements : $first, $second" case s @ Seq(_, _, _) => s"s is a Seq of length three and looks like ${s}" // 请注意,各个元素未绑定到它们自己的名称。 case s: Seq[Int] ifs.length== 4 => s"s is a Seq of Ints of exactly length 4" // 同样,单个元素不绑定到它们自己的名称。 case _ => "找不到匹配项!" }
现场演示
提取first(s) element(s)并将其余部分保留为集合:
def f(ints: Seq[Int]): String = ints match { case Seq(first, second, tail @ _*) => s"The seq has at least two elements : $first, $second. The rest of the Seq is $tail" case Seq(first, tail @ _*) => s"The seq has at least one element : $first. The rest of the Seq is $tail" // 替代语法 // 在这里当然这将永远不会匹配,因为它检查 // 与上述相同 case first +: tail => s"The seq has at least one element : $first. The rest of the Seq is $tail" case _ => "The seq didn't match any of the above, so it must be empty" }
通常,可以用于构建序列的任何形式都可以用于与现有序列进行模式匹配。
请注意,在使用Nil和::在对序列进行模式匹配时将起作用,但确实会将其转换为List,并且可能会产生意外结果。约束自己Seq( ...)并+:避免这种情况。
请注意,虽然使用::不适用于WrappedArray,Vector等等,请参阅:
scala> def f(ints:Seq[Int]) = ints match { | case h :: t => h | case _ => "No match" | } f: (ints: Seq[Int])Any scala> f(Array(1,2)) res0: Any = No match
与 +:
scala> def g(ints:Seq[Int]) = ints match { | case h+:t => h | case _ => "No match" | } g: (ints: Seq[Int])Any scala> g(Array(1,2).toSeq) res4: Any = 1