I am writing simple variable system in Scala. I need a way to nicely hold these AnyVar
s and access them by their string names. I have this object called context to manage it but it is really just a wrapper for HashMap[String, AnyVar]
. I want to find a nicer way to do this.
class Context {
import scala.collection.mutable.HashMap
import scala.reflect.ClassTag
private var variables = HashMap[String, AnyVal] ()
def getVariable (name: String):AnyVal = variables(name)
def setVariable (name: String, value: AnyVal) = variables += ((name, value))
def getVariableOfType[T <: AnyVal : ClassTag] (name:String):T ={
val v = variables(name)
v match {
case x: T => x
case _ => null.asInstanceOf[T]
}
}
}
I really want an implementation that is type safe