Reputation: 14022
I'm trying to grasp scala actors (I'm reading "Scala for the Impatient") and the following short example is not working like I intended.
I have case classes of messages I want to send to the actor:
abstract class Message
case class Sum(x: Int, y: Int) extends Message
case class Stop() extends Message
And how the actor should process them:
import scala.actors.Actor
class Adder(val idx: Int) extends Actor {
def act() {
while(true) {
receive {
case Sum(x: Int, y: Int) => println("Total: " + (x+y) + ", by " + idx)
case Stop => exit()
case _ => println("Wrong message sent to: " + idx + "!")
}
}
}
}
In the main object I create an Adder instance and send some messages:
object Main extends App{
val adder = new Adder(0)
println("Init")
adder ! "Rafael"
adder ! Sum(2, 3)
adder ! Sum(5, 6)
adder ! Stop()
println("goodbye!")
}
But the only outputs are the prints of "Init" and "goodbye!". I can't seem to find what's wrong with the code. I had some working actors before trying this one and just used the same pattern. What am I doing wrong here?
Thanks.
Upvotes: 1
Views: 82
Reputation: 38045
Your program exits before actors gets messages.
You could add Thread.sleep(1000)
before println("goodbye!")
as hotfix.
Instead of Thread.sleep
you could wait for answer from you actor. In this case actor should reply on Stop
message.
Note that scala actors are deprecated, so you should use akka actors.
Also case classes with no arguments are deprecated, use case object Stop extends Message
instead of case class
.
Upvotes: 3