How to get the value of a scala map when the key is a tuple where only the first element is known?
Suppose I have scala immutable Map[(String, Boolean), Set[String]]
, for example:
val myMap = Map(("a",true) -> Set("b","c"))
Now suppose that I know only the first element of a key tuple "a"
. Can (and how if yes) I get the map value for this key if:
1) I know the key can be either ("a", true)
or ("a", false)
(there can be no two keys with the same string as the first element)
2) I don't know that in this case I want to get some kind of concatenation with the possible two values ββlike v1.union(v2)
or v1 ++ v2
etc.
Is there a scala "magic" I could use for example myMap.get(("a", Any))
?
source to share
If you have a lot of such requests, it might be a good idea to replace the card with Map[String, Map[Boolean, Set[String]]
. It is easy to see that they are equivalent: when you have, for example, ("a", false) -> Set()
and ("a", true) -> Set("a")
on your original map, you will have "a" -> Map(false -> Set(), true -> Set("a"))
in a new one.
This will most likely be less memory efficient, especially with these key types. You can improve this by replacing Map[Boolean, Set[String]]
with (Option[Set[String]], Option[Set[String]])
where the first field matches false
and the second matches true
.
When
1) I know the key can be ("a", true) or ("a", false) (there can be no two keys with the same string as the first element)
just use Map[String, (Boolean, Set[String])]
.
source to share