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
?