Skip to content

Instantly share code, notes, and snippets.

@pauldraper
Created December 22, 2013 02:38
Show Gist options
  • Save pauldraper/8077831 to your computer and use it in GitHub Desktop.
Save pauldraper/8077831 to your computer and use it in GitHub Desktop.
Scala BiMap - a bidirectional map for Scala
import scala.collection.mutable.Map
class BiMap[A,B] extends BiMapHelper(Map[A,B](), Map[B,A]()) {
}
object BiMap {
def apply[A,B](elems:(A,B)*) = new BiMap[A,B] ++= elems
}
/**
* This allows a bi-directional map to be created from any two maps.
* These maps must be the inverse of each other to work.
*/
class BiMapHelper[A,B](forward:Map[A,B], backward:Map[B,A]) extends Map[A,B] {
def inverse = new BiMapHelper(backward, forward)
def get(key:A) = forward get key
def iterator = forward.iterator
def +=(kv:(A,B)) = {
forward += kv
backward += kv.swap
this
}
def -=(key:A) = {
backward --= (forward get key)
forward -= key
this
}
override def empty = {
forward.empty
backward.empty
this
}
override def size = forward.size
}
object BiMapHelper {
def apply[A,B](forward:Map[A,B], backward:Map[B,A]) = new BiMapHelper(forward, backward)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment