I found a strange working construct in scala:
(ArrayBuffer[Int]():Seq[Int]) match {
case Nil => "whoo"
case _ => "nayyy"
}
which returns
"whoo"
Apparently this already works partially for Vectors, but not pattern matching. can someone explain me that? Nil
does not have any method named unapply. How is this possible?
With objects, unapply
is not involved (that would be the case if you had used the hypothetical case Nil() => ...
). Instead, the equality is checked using the equals
method.
Equality for collections is defined in terms of their elements. E.g.
List(1,2,3) == Vector(1,2,3) // true!
The same happens with Nil
which equals any empty sequence:
Vector() == Nil // true
collection.mutable.ArrayBuffer() == Nil // true