简体   繁体   中英

how to send message to every Actor (or ActorRef) in array in Akka?

I'm working on eclipse under ubuntu 12.04 with scala 2.10 and Akka 2.2.1.

        // A and B are derived from Node
        val algorithm = if(args(0) > 1)()=> new A else ()=> new B      

       /* alternative: 
        val algorithm = if(args(0) > 1) (()=> system.actorOf(Props(new A), name ="A") )
                        else (()=> system.actorOf(Props(new B),name="B"))
       */       
        // alternative : class work(algorithm: ()=>ActorRef, num:Int) {    
        class work(algorithm: ()=> Node, num: Int){

           val a = Array.fill(num)(algorithm) // here I wanna create an array with num slots 
                                                // and objects of A or B in it
           val rand = new Random(System.currentTimeMillis())
           val randomNode = a(rand.nextInt(5))
           def find (x:Int): Array[ActorRef]{....}
           def receive = {        
              case Rumor => 
            a.foreach(ref=> ref !Init(index, find(x), self))
                randomNode ! Rumor
              case _ => println(...)        
           }    
        }

update:

I create an array which contains Actor or ActorRef(I am not sure which one I am allowed to use in Akka). But eclipse reports on

case Rumor => 
   a.foreach(ref=> ref !Init(index, find(x), self))
   randomNode ! Rumor

I try several times, but it still does not work.

The Array constructor only accepts a length value, not a default value function. The post you reference is explaining how to build a custom data structure that accepts a default value generator.

What you're doing is equivalent to

val arr = new Array[Node](num)
val a = arr(algorithm)

so scala expects an integer index. It's complaining that it can't find a way to convert ()=>Node to an integer to access that index in the array.

To fill an array with a default value you could use Array.fill like this:

val a = Array.fill(num)(algorithm)

The correct way to create an array of actors should be:

val algorithm = if(args(0) > 1) ()=>context.actorOf(Props(new A))  
                else ()=>context.actorOf(Props(new B))  
val a = Array.fill(num)(algorithm())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM