Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a getAs[T] method to Map

Tags:

scala

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] ?

like image 387
vikraman Avatar asked Jan 31 '26 19:01

vikraman


1 Answers

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.

like image 143
om-nom-nom Avatar answered Feb 03 '26 09:02

om-nom-nom