Skip to content

Instantly share code, notes, and snippets.

@milessabin
Last active August 26, 2017 10:28
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save milessabin/aae285025a32fac0f5c1 to your computer and use it in GitHub Desktop.
Save milessabin/aae285025a32fac0f5c1 to your computer and use it in GitHub Desktop.
Trivial type safe heterogenous map using only dependent method types, singleton-typed String literal keys and implicits.
scala> trait Assoc[K] { type V ; val value: V }
defined trait Assoc
scala> def mkAssoc[V0](k: String, v: V0): Assoc[k.type] { type V = V0 } =
| new Assoc[k.type] { type V = V0 ; val value = v }
mkAssoc: [V0](k: String, v: V0)Assoc[k.type]{type V = V0}
scala> implicit def nameAssoc = mkAssoc("Name", "Mary")
nameAssoc: Assoc[String("Name")]{type V = String}
scala> implicit def ageAssoc = mkAssoc("Age", 23)
ageAssoc: Assoc[String("Age")]{type V = Int}
scala> def lookup(k: String)(implicit assoc: Assoc[k.type]): assoc.V = assoc.value
lookup: (k: String)(implicit assoc: Assoc[k.type])assoc.V
scala> lookup("Name")
res0: String = Mary
scala> lookup("Age")
res1: Int = 23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment