Search code examples
scalaakkaactor

Akka Receive Method case mutable.Map gives a runtime error


I'm trying to run the receive method of Akka Actor in the following way:

  def receive = {
    case  x: collection.mutable.Map[String, collection.mutable.Map[String,Float]]=>
    insertValueIntoTable(x)
  }

I'm able to compile this with no issues, but I get the error:

Error:(83, 57) ']' expected but '.' found. case x: collection.mutable.Map[String, collection.mutable.Map[String,Float]]=>

Is there any other way I can pass a mutable map which has a value as another mutable map? Any help is appreciated.


Solution

  • It is important to mention that this statement (if it worked) would match any mutable.Map due to type erasure:

    [...] To implement generics, the Java compiler applies type erasure to:

    • Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
    • [...]

    Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

    To get around that, you can simply create a wrapper class which carries your map:

    case class MapMessage(map: mutable.Map[String, mutable.Map[String,Float]])
    

    And then in your receive method:

    def receive = {
        case  MapMessage(x)=>
            insertValueIntoTable(x)
    }
    

    Regardless of the type you want to pass around it is usually good to have case classes as wrapper, and if it is only to give the message a more meaningful name.

    Regarding the error, it is hard to tell without more code, but you should get around it with this method anyways.