如何向Akka中的数组中的每个Actor(或ActorRef)发送消息?

时间:2013-10-02 02:25:36

标签: scala akka

我正在使用scala 2.10和Akka 2.2.1在ubuntu 12.04下进行eclipse。

        // 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(...)        
           }    
        }

更新

我创建了一个包含Actor或ActorRef的数组(我不确定哪个允许在Akka中使用)。但是eclipse报道了

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

我尝试了几次,但它仍然不起作用。

2 个答案:

答案 0 :(得分:5)

Array构造函数只接受长度值,而不是默认值函数。您引用的帖子解释了如何构建接受默认值生成器的自定义数据结构。

你所做的相当于

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

因此scala需要一个整数索引。它抱怨它无法找到将()=>Node转换为整数的方法来访问数组中的索引。

要使用默认值填充数组,您可以使用Array.fill,如下所示:

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

答案 1 :(得分:1)

创建actor数组的正确方法应该是:

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