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.
The comparison Vector[Int]() == Nil
is possible because there is no constraint on the type level for what you compare; that allows the implementation of equals
for collections, on the other hand, to perform an element by element comparison irrespective of the collection type:
Vector(1, 2, 3) == List(1, 2, 3) // true!
In pattern matching, you cannot have a case for an empty list (Nil
) when the type is not related to list (it's a Vector
).
You can do this however:
val x = Vector(1, 2, 3)
x match {
case y +: ys => println("head: " + y + "; tail: " + ys)
case IndexedSeq() => println("empty vector")
}
But I would suggest just to use the default case here, because if x
does not have a head element, it must be technically empty:
x match {
case y +: ys => println("head: " + y + "; tail: " + ys)
case _ => println("empty vector")
}