I have written a generic function to get a value from a HashMap[String, AnyVal]. This method returns a value from the name but also has a functionality to make sure it is of a specific type:
class Context {
private var variables = HashMap[String, Any] ()
def getVariable (name: String):Any = variables(name)
def setVariable (name: String, value: Any) = variables += ((name, value))
def getVariableOfType[T <: AnyVal] (name:String):T ={
val v = variables(name)
v match {
case T => v.asInstanceOf[T]
case _ => null.asInstanceOf[T]
}
}
}
The function getVariableOfType[T <: AnyVal] will not compile because it says "Cannot resolve symbol T" at the line case T => v.asInstanceOf[T]
case something: T => v.asInstanceOf[T] /*or better just: something */. Though it is not recommended, you should useTypeTags.case.v match { case _ : T => v.asInstanceOf[T]}, otherwise the compiler tries to matchvto an already defined value calledT.