Last active
August 26, 2017 10:28
-
-
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.
This file contains 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
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