In this post we’ll look at MapOps
and the goodies it provides to work with Map
s. Examples galore!
Altering a Map
1 | @ import scalaz._ |
alter
lets you change the values associated with keys. In the example, we’re altering the value associated with key b
. Since there may or may not be a value associated with b
, we get an Option
which we’ve named as maybeValue
. We then use the some { ... } none { ... }
construct to either add 1 in case there’s a value or initialize the key with 0. Also, since we need to return Option
s, we use some
and none
again.
1 | @ m1.alter("d") { maybeValue => maybeValue some { v => some(v + 1) } none { some(0) } } |
If the key does not exist, it will be added to the map.
Intersection
1 | @ m1.intersectWith(m2) { _ + _ } |
intersectWith
lets you calculate the intersection of two maps. It expects a function that will accept values v1
and v2
from both the maps and return a new value which will become the value associated with the key in the new map. If you want to analyze the key before returning the value, you can use intersectWithKey
which expects a function (k, v1, v2) => { ... }
.
Mapping Keys
1 | @ m1 mapKeys { _.toUpperCase } |
mapKeys
lets you change the keys without changing the values associated with them. Here, we’re converting them to uppercase.
Union
1 | @ m1.unionWith(m2){ _ + _ } |
unionWith
lets you calculate the union of two maps and expects a function that will accept values v1
and v2
from both maps and return a new value which will become the value associated with the key in the new map. Similarly, there’s unionWithKey
which will pass the key as the first argument to the function.
Inserting a Value
1 | @ m1.insertWith("a", 99) { _ + _ } |
insertWith
lets you insert a new key-value pair into the map. It also expects a function which will take values v1
and v2
as arguments to deal with cases where the key you’re trying to add already exists.
Conclusion
This brings us to the end of the post on MapOps
. These extra functions make it very easy to work with an immutable Map
by providing extra functionality not present in the Scala core library.