Pattern Matching “case Nil” for Vector

前端 未结 1 1509
被撕碎了的回忆
被撕碎了的回忆 2021-02-12 19:11

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.

相关标签:
1条回答
  • 2021-02-12 19:54

    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")
    }
    
    0 讨论(0)
提交回复
热议问题