Adding getAs [T] Method to Map

I would like to add a method getAs[T](key)

to Map

that will return a value asInstanceOf[T]

, which I find useful when the type is value Any

. This is my attempt at using a 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 will not let me do it, because the methods +

, -

, iterator

, and get

are not defined, I really do not want to define.

How should I do it? Is there a better approach to this getAs[T]

?

+3


source to share


1 answer


You can use the my-library enrichment pattern (former pimp is 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 you need to save the imported map2MapT where you want to use getA.

In scala 2.10 you can use so called 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 create wrappers, you can use another 2.10 class - value class:

implicit class MapT(val underlying: Map[Any,Any]) extends AnyVal {
      def getAs[T](key: Any): T = underlying.apply(key).asInstanceOf[T]
}

      

Thus, the compiler will shrink the MapT class and omit the getAs [T] method at each call site.

+9


source







All Articles