Skip to content

Instantly share code, notes, and snippets.

@pathikrit
Last active March 8, 2016 19:58
Show Gist options
  • Select an option

  • Save pathikrit/90ce7fa6d34c1bc7eb66 to your computer and use it in GitHub Desktop.

Select an option

Save pathikrit/90ce7fa6d34c1bc7eb66 to your computer and use it in GitHub Desktop.
Bi-directional map in Scala
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