Scala Map pattern matching

懵懂的女人 提交于 2019-12-12 08:08:42

问题


How to do pattern matching on a Map in Scala ?

A (non working) attempt includes,

Map("a"->1, "b"->2, "c"->3) match {
  case Map(a,b,_*) => a
}

which errs with

value Map is not a case class, nor does it have an unapply/unapplySeq member
              case Map(a,b,_*) => a

The error is indicative enough, yet how to enrich Map with an unapply method for pattern matching ?

Many Thanks

Update

Following @Paul's comment, a neater use case may be like this,

Map("a"->1, "b"->2, "c"->3) match {
  case Map("b"->2,_*) => "222"
}

namely, in this case, if map contains key b that maps onto value 2.


回答1:


Most easy way is tramsform Map to List:

Map("a"->1, "b"->2, "c"->3).to[List] match {
  case List(a,b,_*) => a
}



回答2:


An approach to enriching Map with an unapplySeq method for pattern matching includes this,

object MapExtractor {
  def unapplySeq[A <% Ordered[A], B <% Ordered[B]]
      (s: Map[A,B]): Option[Seq[(A,B)]] = Some(s.toSeq.sorted) 
}

where the sorting approach may be changed to any orderable (items comparable) logic. In this example,

Map("b"->2, "a"->1, "c"->3) match {
  case MapExtractor ( x, xs @ _* ) => println(s"x: $x") ; println(s"xs: $xs") 
}

delivers

x: (a,1)
xs: ArrayBuffer((b,2), (c,3))


来源:https://stackoverflow.com/questions/25178371/scala-map-pattern-matching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!