Skip to content

Instantly share code, notes, and snippets.

@markoutso
Created August 12, 2016 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markoutso/078370d69d4cbe4d041337481da6a5e5 to your computer and use it in GitHub Desktop.
Save markoutso/078370d69d4cbe4d041337481da6a5e5 to your computer and use it in GitHub Desktop.
// Similar to http://stackoverflow.com/questions/9850786/is-there-such-a-thing-as-bidirectional-maps-in-scala#9851520
object BiMap {
private[BiMap] trait MethodDistinctor
implicit final object MethodDistinctor extends MethodDistinctor
def apply[X, Y](tuples: (X, Y)*) = new BiMap(tuples.toMap, tuples.map(_.swap).toMap)
def apply[X, Y](m: Map[X, Y]) = new BiMap(m, m.toSeq.map(_.swap).toMap)
}
class BiMap[X, Y](m1: Map[X, Y], m2: Map[Y, X]) {
def apply(x: X): Y = m1(x)
def apply(y: Y)(implicit d: BiMap.MethodDistinctor): X = m2(y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment