1
votes

I am new to Scala and also to Actors. So, I am little bit confused. The first task I worked with is the ping pong example. The code looks as follows

class PingPong(sendTo: Actor, val name: String) extends Actor {
  def act {
   loop {
     receive {
        case x:Int =>
          println(name + " received " + x)
          Thread.sleep(500)
          if (sendTo == null)
            sender ! (x+1)
          else
            sendTo ! (x+1)
      }
    }
  }
} 

object PingPongMain extends App {
  val pong = new PingPong(null, "pong")
  val ping = new PingPong(pong, "ping")
  ping.start()
  pong.start()
  ping ! 0
}

Output is
ping received 0
pong received 1
...

So, how does it get evaluated?
So far, I know .start() calls act().
What happens after then?
ping ! 0 gets called. Does this mean that 0 is send to the address where ping is instantiated? Then does it call act? What if there were more than one method?
But how does pong get called? I mean how does it know where sendTo is?

Also, is it possible to do this with something like val ping/pong = actor {} instead of with extends Actor?

1
Scala Actors are deprecated, use Akka Actors.Ryan

1 Answers

0
votes
  • You should pass around ActorRefs not Actors. which are resolved from an ActorSystem
  • Each actor only needs to define def receive = ... so remove the act and loop ceremony around it
  • There is no need to start the actor. It will happen automatically when you get the actorRef from the ActorSystem.
  • Extend the Actor trait. I've never seen it done another way.