Created
January 29, 2015 08:30
-
-
Save tyrcho/491353e1497a2adf0543 to your computer and use it in GitHub Desktop.
Recursive (deep) merge of 2 maps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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