Created
January 17, 2017 16:54
-
-
Save akozhemiakin/ebfe1025e18a6e39886bcf8aef059d3e to your computer and use it in GitHub Desktop.
Typeclass for Scala map that allows to get values and ensure their type
This file contains hidden or 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
import scala.collection.Map | |
import scala.reflect.ClassTag | |
final case class TypefullMapOps[K, V, M <: Map[_, _]](m: M)(implicit ev: M <:< Map[K, V]) { | |
def getT[A <: V : ClassTag](k: K): Option[A] = m.get(k) match { | |
case Some(x) => x match { | |
case v: A => Some(v) | |
case _ => throw new RuntimeException | |
} | |
case _ => None | |
} | |
def getOrElseT[A <: V : ClassTag](k: K, d: A): A = m.get(k) match { | |
case Some(x) => x match { | |
case v: A => v | |
case _ => throw new RuntimeException | |
} | |
case _ => d | |
} | |
} | |
implicit def toTypefullMapOps[K, V, M <: Map[_, _]](m: M)(implicit ev: M <:< Map[K, V]): TypefullMapOps[K, V, M] = | |
TypefullMapOps(m) | |
val m = Map("foo" -> 5.2, "bar" -> true, "baz" -> "go") | |
m.getT[Boolean]("bar") | |
m.getOrElseT[Double]("foo", 10.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment