Vector的模式匹配“case Nil”

时间:2013-11-03 19:43:27

标签: scala

在阅读post关于如何在Vector(或任何实现Seq的集合)上使用模式匹配之后,我在此集合上测试了模式匹配。

scala> x // Vector
res38: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)

scala> x match {
     |    case y +: ys => println("y: " + "ys: " + ys)
     |    case Nil => println("empty vector")
     | }
<console>:12: error: pattern type is incompatible with expected type;
 found   : scala.collection.immutable.Nil.type
 required: scala.collection.immutable.Vector[Int]
Note: if you intended to match against the class, try `case _: <none>`
                 case Nil => println("empty vector")
                      ^

以下dhg的答案解释了+:

object +: {
  def unapply[T](s: Seq[T]) =
    s.headOption.map(head => (head, s.tail))
}

REPL告诉我

scala> Vector[Int]() == Nil
res37: Boolean = true

...为什么我不能将此case Nil语句用于Vector

1 个答案:

答案 0 :(得分:27)

比较Vector[Int]() == Nil是可能的,因为您比较的类型级别没有约束;另一方面,它允许为集合实现equals,无论集合类型如何,都可以逐元素地执行:

Vector(1, 2, 3) == List(1, 2, 3)  // true!

在模式匹配中,当类型与列表无关时(Nil),您不能拥有空列表(Vector)的大小写。

你可以这样做:

val x = Vector(1, 2, 3)

x match {
  case y +: ys => println("head: " + y + "; tail: " + ys)
  case IndexedSeq() => println("empty vector")
}

但我建议在这里使用默认情况,因为如果x没有head元素,那么它必须在技术上是空的:

x match {
  case y +: ys => println("head: " + y + "; tail: " + ys)
  case _ => println("empty vector")
}
相关问题