Pattern Comparison with Scala Map Entries

Is there any Scala trick to enable map matching? In other words, I would like to have an extractor that, in addition to the card instance, also accepted a key value, which would mean that I want this template to match only if the appropriate value is an instance of the Card and there is an entry with the given key in it, and the value for This entry must match recursive pattern matching.

Something like that:

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

Update:

I found a way to get closer to the goal, but this is still not perfect, because it involves defining synthetic key 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") } 

A similar question: Is it possible to configure extractors with parameters in the body of the case statement (or anywhere else that the extractor will use)?

Feature Request: SI-5435

+7
scala pattern-matching
source share
1 answer

Perhaps you are looking for a solution that you really don't need? I can not imagine extractors. You can use PF if you want to combine key-value pairs:

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

The return type is the [Unit] option, because we use the collectFirst and println functions

+1
source share

All Articles