20

After reading this post on how to use pattern matching on Vector (or any collection that implements Seq), I tested pattern matching on this collection.

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")
                      ^

Here's dhg's answer that explains +::

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

REPL shows me that

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

... so why can I not use this case Nil statement for an Vector?

4

1 回答 1

31

比较Vector[Int]() == Nil是可能的,因为您比较的类型没有限制;equals另一方面,它允许 for 集合的实现执行逐个元素的比较,而与集合类型无关:

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

Nil在模式匹配中,当类型与列表无关(它是 a )时,您不能有空列表 ( ) 的情况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")
}
于 2013-11-03T19:47:02.670 回答