tecfield
tecfield

Reputation: 203

Extension Method for Map in Scala

I am a novice in the Scala world! I am trying to develop some helpers to make my life easier around Scala code. For instance, one of the pieces that I am trying to get it to work is as below -

object Helpers{
  implicit class MapExt(val self: Map[String, Any]) extends AnyVal {
      // gets a map value for specified key casting as required type
      def GetValueAs[T](key: String): T = self(key).asInstanceOf[T];
  }
}

The logic behind this code is that I have a String to Any map that I need to cast values at run-time. What I am trying to achieve here is not important but what's important is that how we do this in Scala. How can I have an extension method that works for a specific type of generic type (in this case Map[String, Any]) and that method is itself a generic type. The code as above gives me a compile time error if I try to use it as -

myMap.GetValueAs[Date]("start_date")

Error: value GetValueAs is not a member of scala.collection.immutable.Map[String,Any]

Can someone please help to get just his simple example to work. That would be a great help and I appreciate it!

Thanks

Upvotes: 1

Views: 1406

Answers (1)

0__
0__

Reputation: 67290

You need to bring your extension methods into scope, i.e. by importing them:

object Helpers {
  implicit class MapExt(val self: Map[String, Any]) extends AnyVal {
    // gets a map value for specified key casting as required type
    def getValueAs[A](key: String): A = self(key).asInstanceOf[A]
  }
}

import Helpers._  // !
Map("foo" -> 2, "bar" -> 3.45).getValueAs[Int]("foo")  // works

Upvotes: 3

Related Questions