how can I store a scala actor reference?

Hello I am new to Scala and I have failed to figure out how one can store an actor reference within a second actor, for sending a message at a later time. In my code I try to send a test message to one actor. when it receives this message it should store the reference (OutputChannel) to the second actor and at a later time should be able to send a message to the second actor. I did not want to use the reply() as I need the message to be sent only when i invoke the respond. Here is the code. Thanks for any help!

import scala.actors.Actor
import scala.actors.Actor._
import scala.collection.mutable.ArrayBuffer 
import scala.actors.OutputChannel

object testactors {

    case object TestMessage
    case object Respond

    class TestActor(name: String) extends Actor {
        private var source : ArrayBuffer[OutputChannel[Any]] = new ArrayBuffer

        def act() {
            loop {
                react{
                    case TestMessage =>
                        println("i received a TestMessage " + name)
                        source += sender
                    case Respond =>
                        println("i received a ResponseMessage " + name)
                }
            }
        }

        def sendMessage(dest: Actor) = dest ! TestMessage

        def respond = {
            println("responding... " + name)
            source(0) ! Respond
        }
    }


    def main(args: Array[String]) {
        val actor1 = new TestActor("one")
        actor1.start

        val actor2 = new TestActor("two")
        actor2.start

        actor1.sendMessage(actor2)

        Thread.sleep(5000)

        actor2.respond
    }
}
7
задан Vasil Remeniuk 10 February 2011 в 15:08
поделиться