Scala Map pattern matching

人走茶凉 提交于 2019-12-03 14:27:50

Most easy way is tramsform Map to List:

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

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