Scala Map 模式匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25178371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala Map pattern matching
提问by elm
How to do pattern matching on a Mapin Scala ?
如何Map在 Scala 中对 a 进行模式匹配?
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 Mapwith an unapplymethod for pattern matching ?
错误已经足够了,但如何丰富模式匹配Map的unapply方法?
Many Thanks
非常感谢
Update
更新
Following @Paul's comment, a neater use case may be like this,
按照@Paul 的评论,一个更简洁的用例可能是这样的,
Map("a"->1, "b"->2, "c"->3) match {
case Map("b"->2,_*) => "222"
}
namely, in this case, if map contains key bthat maps onto value 2.
即,在这种情况下,如果 map 包含b映射到 value 的键2。
采纳答案by elm
An approach to enriching Mapwith an unapplySeqmethod for pattern matching includes this,
使用模式匹配方法进行丰富Map的unapplySeq方法包括:
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))
回答by Yuriy
Most easy way is tramsform Mapto List:
最简单的方法是tramsformMap到List:
Map("a"->1, "b"->2, "c"->3).to[List] match {
case List(a,b,_*) => a
}

