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
scala pattern-matching
Jiří Vypědřík
source share