Instantiating and starting a Scala Actor in a Map
- by Bruce Ferguson
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!!