Scala Map模式匹配 [英] Scala Map pattern matching

查看:157
本文介绍了Scala Map模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Scala中的Map上进行模式匹配?

How to do pattern matching on a Map in Scala ?

一次(无效)尝试,

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

哪个错误

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

该错误足以说明问题,但是如何使用unapply方法进行模式匹配来丰富Map呢?

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

非常感谢

更新

在@Paul的评论之后,更整洁的用例可能是这样的,

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"
}

即在这种情况下,如果映射包含键b并映射到值2 上,则为.

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

推荐答案

使用unapplySeq模式匹配方法丰富Map的方法包括

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) 
}

可以将排序方法更改为任何 orderable (可比较的项目)逻辑.在此示例中,

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") 
}

交付

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

这篇关于Scala Map模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆