简体   繁体   English

与Scala Map条目匹配的模式

[英]Pattern matching against Scala Map entries

Is there any Scala trick to enable pattern matching against map keys? 是否有任何Scala技巧可以启用与地图键的模式匹配? In other words, I'd like to have an extractor that beside the Map instance accepted also a key value that would mean I want this pattern to match only if the matchable value is an instance of Map and there is an entry with the given key in it and the value for this entry be subject to recursive pattern matching. 换句话说,我想在Map实例旁边有一个提取器也接受一个键值,这意味着只有当matchable值是Map的一个实例并且有一个带有给定键的条目时,我希望这个模式匹配在其中,此条目的值受递归模式匹配的影响。

Something like this: 像这样的东西:

myMap match {
    case MyMap("a")(a) => // do smth with value a
    case MyMap("b")(MyMap("c")(c)) => // do smth with value c
}

Update: 更新:

I've found some way to approach closer to the goal, but it's still not perfect because it implies definition of synthetic key-value-holders: 我找到了一些接近目标的方法,但它仍然不完美,因为它意味着合成键值持有者的定义:

case class MapKey[K](key: K) {
  def unapply(o: Any) = o match {
    case m: Map[K, _] ⇒ m.get(key)
    case _ ⇒ None
  }
}

val m1 = Map("a" → "aa", "b" → Map("c" → "cc"))
val m2 = Map("a" → "aa", "d" → "dd")

val b = MapKey("b")
val c = MapKey("c")
val d = MapKey("d")

for (m ← List(m1, m2)) m match {
  case b(c(x)) ⇒ println(s"b > c: $x")
  case d(x) ⇒ println(s"d: $x")
}

Similar question: Can extractors be customized with parameters in the body of a case statement (or anywhere else that an extractor would be used)? 类似的问题: 可以在case语句的主体中(或者在使用提取器的任何其他地方)使用参数自定义提取器吗?

Feature request: SI-5435 特征要求: SI-5435

Maybe you are looking for solution that you don't really need? 也许您正在寻找您不需要的解决方案? Can't imagine extractors here. 无法想象这里的提取器。 You can use PF if you want to match key-value pairs: 如果要匹配键值对,可以使用PF:

val map = Map[String, String]("a" -> "b")

def matchTuple[A,B,C](map: Map[A,B])(pf: PartialFunction[(A,B), C]) = 
  map.collectFirst(pf)

matchTuple(map) {
  case ("a", b) => println("value for a is " + b)
}

Return type is Option[Unit] because we use collectFirst and println 返回类型是Option [Unit],因为我们使用collectFirst和println

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM