Below is a very concise and reasonably idiomatic way of writing this in Scala:
def mergeWith[K, X, Y, Z](xs: Map[K, X], ys: Map[K, Y])
(f: (X, Y) => Z): Map[K, Z] =
xs.flatMap {
case (k, x) => ys.get(k).map(k -> f(x, _))
}
Please note that I use Mapinstead HashMapand slightly changed some identifier names. I also included a function in my own parameter list, which can make the syntax a bit cleaner for the user.
, , . - (k, v) xs ys.get(k), Option[Y], Some[Y], ys None . Map Option, Y ( ) (K, Z).
, ys.get(k).map(k -> f(x, _)) Option[(K, Z)], . Map xs, Seq[Option[(K, Z)]], flatMap, Map[K, Z], ( , .
:
scala> val mapX = Map('a -> 1, 'b -> 2)
mapX: scala.collection.immutable.Map[Symbol,Int] = Map('a -> 1, 'b -> 2)
scala> val mapY = Map('b -> "foo", 'c -> "bar")
mapY: scala.collection.immutable.Map[Symbol,String] = Map('b -> foo, 'c -> bar)
scala> mergeWith(mapX, mapY) { (x, y) => (x, y) }
res0: Map[Symbol,(Int, String)] = Map('b -> (2,foo))
, .