5

Why does the following:

val x: Seq[Any] = Vector.empty
x match {
 case Nil => 1
 case _ => 2
}

where Vector.empty internally equates to:

private[immutable] val NIL = new Vector[Nothing](0, 0, 0)
override def empty[A]: Vector[A] = NIL

match Nil and return 1? Isn't Nil only a specific subtype of Seq?

The answer remains the same if I use the more generic Seq.empty. Why is that?

Maths noob
  • 1,684
  • 20
  • 42
  • 1
    I think it is because `Vector[Nothing]` and `Nil` are instances of `AbstractSeq[Nothing]`. `Seq.empty` also has the same type. – Duelist Jul 16 '18 at 12:11

1 Answers1

5

By specification this pattern matches when x == Nil, which for Seq is defined to be

true if that is a sequence that has the same elements as this sequence in the same order, false otherwise

So Vector.empty == Nil is true.

If you actually want to check that you have exactly the Nil object in the pattern match, use one of the following ways:

case _: Nil.type =>
case x if x eq Nil =>
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487