I would like to add a getAs[T](key) method to Map, that would return the value asInstanceOf[T], which I find useful when the value type is Any. This is my attempt using trait.
trait MapT extends Map[Any, Any] {
def getAs[T](key: Any): T = super.apply(key).asInstanceOf[T]
}
val map = new Map[Any,Any] with MapT
But, the compiler wouldn't let me do this since the +, -, iterator and get methods are not defined, which I really don't want to define.
How do I go about doing this? Is there a better approach to getAs[T] ?
You can go with enrich-my-library pattern (former pimp-my-library):
class MapT(underlying: Map[Any,Any]) {
def getAs[T](key: Any): T = underlying.apply(key).asInstanceOf[T]
}
implicit def map2MapT(m: Map[Any,Any]) = new MapT(m)
Now all you need is to keep map2MapT imported where you want getAs to be used.
In scala 2.10 you can made use of so-named implicit classes and write the same as:
implicit class MapT(underlying: Map[Any,Any]) {
def getAs[T](key: Any): T = underlying.apply(key).asInstanceOf[T]
}
If you don't want to produce wrappers, you can use another 2.10 feature -- value class:
implicit class MapT(val underlying: Map[Any,Any]) extends AnyVal {
def getAs[T](key: Any): T = underlying.apply(key).asInstanceOf[T]
}
So compiler will cut MapT class and leave getAs[T] method inlined at every call site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With