Skip to content

Instantly share code, notes, and snippets.

@joshlemer
Created July 20, 2018 12:48
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 joshlemer/788950a50ebe03453975720c4d20507b to your computer and use it in GitHub Desktop.
Save joshlemer/788950a50ebe03453975720c4d20507b to your computer and use it in GitHub Desktop.
DMap
package dmap
import scala.reflect.runtime.universe._
import DMap._
class DMap private(underlying: Map[Any, Entry]) {
def get[T](key: Any)(implicit tt: TypeTag[T]): Option[T] = {
underlying.get(key) match {
case Some(Entry(v, t)) if t <:< tt.tpe => Some(t.asInstanceOf[T])
case _ => None
}
}
def +[T](kv: (Any, T))(implicit tt: TypeTag[T]): DMap = new DMap(underlying + (kv._1 -> Entry(kv._2)))
}
object DMap {
val empty = new DMap(Map())
def apply(kvs: (Any, Entry)*): DMap = new DMap(kvs.toMap)
class Entry private (val value: Any, val tpe: Type)
object Entry {
implicit def apply[T](value: T)(implicit tt: TypeTag[T]): Entry = new Entry(value, tt.tpe)
def unapply(entry: Entry): Option[(Any, Type)] = Some((entry.value, entry.tpe))
}
}
object Foo extends App {
trait F[X]
val x = DMap("hello" -> 1, "howdy" -> new F[List[Char]] {})
println(x.get[Int]("hello")) // Some
println(x.get[List[Int]]("hello")) // None
println(x.get[F[List[Char]]]("howdy")) // Some
println(x.get[Any]("howdy")) // Some
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment