Here is the main problem with what you want:
def get(key: String): Option[T] = ... val r = map.get("key")
Type r will be determined from the return type get - so what should this type be? How can this be determined? If you make this a type parameter, then this is relatively easy:
import scala.collection.mutable.{Map => MMap} val map: MMap[String, (Manifest[_], Any) = MMap.empty def get[T : Manifest](key: String): Option[T] = map.get(key).filter(_._1 <:< manifest[T]).map(_._2.asInstanceOf[T]) def put[T : Manifest](key: String, obj: T) = map(key) = manifest[T] -> obj
Example:
scala> put("abc", 2) scala> put("def", true) scala> get[Boolean]("abc") res2: Option[Boolean] = None scala> get[Int]("abc") res3: Option[Int] = Some(2)
The problem, of course, is that you have to tell the compiler which type you want to save on the map under this key. Unfortunately, this does not happen: the compiler cannot know what type will be stored under this key during compilation.
Any decision you take will end with the same question: anyway, you need to tell the compiler which type should be returned.
Now this should not be a burden in the Scala program. Take this r above ... then you will use this r for something, right? What you use for this will have methods that correspond to some type, and since you know what methods are, then you should also know what should be of type r .
If this is not so, then there is something fundamentally wrong in the code - or maybe you didnβt switch from the fact that the card did not know what you would do with it.
source share