MatchError when match receives an IndexedSeq but not a LinearSeq

前端 未结 2 531
暖寄归人
暖寄归人 2020-12-12 00:20

Is there a reason that match written against Seq would work differently on IndexedSeq types than the way it does on LinearSeq

2条回答
  •  感动是毒
    2020-12-12 01:23

    You can't use :: for anything other than List. The Vector is failing to match because :: is a case class that extends List, so its unapply method does not work for Vector.

    val a :: b = List(1,2,3)    // fine
    val a :: b = Vector(1,2,3)  // error
    

    But you can define your own extractor that works for all sequences:

    object +: {
      def unapply[T](s: Seq[T]) =
        s.headOption.map(head => (head, s.tail))
    }
    

    So you can do:

    val a +: b = List(1,2,3)   // fine
    val a +: b = Vector(1,2,3) // fine
    

提交回复
热议问题