Skip to content

Instantly share code, notes, and snippets.

@tyrcho
Created January 29, 2015 08:30
Show Gist options
  • Save tyrcho/491353e1497a2adf0543 to your computer and use it in GitHub Desktop.
Save tyrcho/491353e1497a2adf0543 to your computer and use it in GitHub Desktop.
Recursive (deep) merge of 2 maps
object Maps {
implicit class MergableMap[K](map: Map[K, _]) {
/**
* Override values from this with values from that.
*/
def deepMerge(that: Map[K, _]): Map[K, _] =
(for (k <- map.keys ++ that.keys) yield {
val newValue =
(map.get(k), that.get(k)) match {
case (Some(v), None) => v
case (None, Some(v)) => v
case (Some(v1), Some(v2)) =>
if (v1.isInstanceOf[Map[K, _]] && v2.isInstanceOf[Map[K, _]])
v1.asInstanceOf[Map[K, _]] deepMerge v2.asInstanceOf[Map[K, _]]
else v2
case (_, _) => ???
}
k -> newValue
}).toMap
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment