MatchError when match receives an IndexedSeq but not a LinearSeq

前端 未结 2 522
暖寄归人
暖寄归人 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:22

    Followed pattern match works for List, Seq, LinearSeq, IndexedSeq, Vector.

      Vector(1,2) match {
      case a +: as => s"$a + $as"
      case _      => "empty"  
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题