Search code examples
scaladictionarycastingattributesany

Scala: Accessing/casting entries from Map[String, Any] or better alternative


With pattern matching I am extracting attributes from an AST and saving them in a Map[String, Any], because they can be Strings, Integers, Lists etc. Now I want to use the attributes in a case class. For getting the elements I wrote this method:

def getAttr(attr: Map[String, Any], key : String):Any = {
   val optElem = attr.get(key) match {
     case Some(elem) => elem
     case _ => throw new Exception("Required Attribute " + key + " not found")
  }
}

Because I always know what type every attribute value is I want to use the value like this:

case class Object1(id: String, name: String)

Object1("o1", getAttr(attrMap, "name").asInstanceOf[String])

But I get the error "scala.runtime.BoxedUnit cannot be cast to java.lang.String"

What am I doing wrong? Or is there a better way to collect and use my attributes?


Solution

  • Your implementation of getAttr has type Unit since you return result of assignment of value to optElem

    To fix:

    def getAttr(attr: Map[String, Any], key : String):Any = {
      attr.get(key) match {
        case Some(elem) => elem
        case _ => throw new Exception("Required Attribute " + key + " not  found")
      }
    }