Instantiating and starting a Scala Actor in a Map
        Posted  
        
            by 
                Bruce Ferguson
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Bruce Ferguson
        
        
        
        Published on 2011-01-07T19:47:42Z
        Indexed on 
            2011/01/07
            19:54 UTC
        
        
        Read the original article
        Hit count: 365
        
I'm experimenting with a map of actors, and would like to know how to instantiate them and start them in one fell swoop...
import scala.actors.Actor
import scala.actors.Actor._
import scala.collection.mutable._
abstract class Message
case class Update extends Message
object Test {
    val groupings = "group1" :: "group2" :: "group3":: Nil
    val myActorMap = new HashMap[String,MyActor]
    def main(args : Array[String]) {
        groupings.foreach(group => myActorMap += (group -> new MyActor))
        myActorMap("group2").start
        myActorMap("group2") ! Update
    }
}
class MyActor extends Actor {
    def act() {
        loop {
            react {
                case Update =>
                    println("Received Update")
                case _ =>
                    println("Ignoring event")
            }
        }
    }   
}
The line:
    myActorMap("group2").start
will grab the second instance, and let me start it, but I would like to be able to do something more like:
        groupings.foreach(group => myActorMap += (group -> (new MyActor).start))
but no matter how I wrap the new Actor, the compiler complains with something along the lines of:
type mismatch; found : scala.actors.Actor required: com.myCompany.test.MyActor
or various other complaints. I know it must be something simple to do with anonymous classes, but I can't see it right now. Any suggestions? Thanks in advance!!
© Stack Overflow or respective owner