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):
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:
If you don’t want to produce wrappers, you can use another 2.10 feature — value class:
So compiler will cut MapT class and leave getAs[T] method inlined at every call site.