Last active
March 8, 2016 19:58
-
-
Save pathikrit/90ce7fa6d34c1bc7eb66 to your computer and use it in GitHub Desktop.
Bi-directional map in Scala
This file contains hidden or 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
| class BiMap[A, B] private(var a2b: Map[A, B], var b2a: Map[B, A]) extends Tuple2(a2b, b2a) with collection.mutable.MapLike[A, B, BiMap[A, B]] { | |
| override def +=(kv: (A, B)) = { | |
| a2b = a2b + kv | |
| b2a = b2a + kv.swap | |
| this | |
| } | |
| override def -=(a: A) = { | |
| get(a).foreach {b => b2a = b2a - b} | |
| a2b = a2b - a | |
| this | |
| } | |
| override def get(a: A) = a2b get a | |
| override def empty = BiMap.empty | |
| override def iterator = a2b.iterator | |
| override def seq = a2b.seq | |
| } | |
| object BiMap { | |
| def empty[A, B] = new BiMap(Map.empty[A, B], Map.empty[B, A]) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment