0

Given the Scala code below:

actor1

 actor2 ! 'some_message

actor2

 receive (or react)
  {
    case 'some_message
         sender ! 'ok_message

What info about the sender (actor1) can actor2 get ?

How can it tell which actor the message came from if more than one actor can send the same message to actor2 ? Is there metadata in sender that can be queried ?

Am a newcomer to Scala. Thanks for your patience.

...Ken R

  • Scala actors are deprecated since Scala 2.10 user Akka framework for actors – 4lex1v Aug 07 '13 at 21:30
  • 1
    I generally discourage any use of `sender` (Akka actors) because it limits the flexibility with which you can construct processing topologies. If you always reply to `sender` you message interaction patterns are strictly tree-structured. Instead, I always include a reply-to property in the message. Recently I've taken to making it a repeated parameter (of type `ActorRef`, of course) and I send any reply to all of them. It's more flexible and more importantly avoids the syntactic noise of using `Option[ActorRef]`. – Randall Schulz Aug 07 '13 at 23:55
  • 1
    The use of `sender` does not restrict your interaction patterns in any way because you have full control over that value, just the same as if it were part of the message. The most common patterns are supported out of the box—use sending actor or keep previous sender—but you are free to stick in anything you want. It would even be possible to construct a broadcast ref (e.g. using `ask()` and an appropriate `onComplete`) to model your case of replying to multiple actors. Putting that in the message is of course possible but not always desirable (if the message type is unrelated to actors). – Roland Kuhn Aug 08 '13 at 06:06

1 Answers1

0

You can actually send the actor that sent the original message as part of the message.

actor1

actor2 ! ("message", self)

actor2

receive (or react) {
    case (string: String, sender: Actor) => {
        sender ! "another message"
    }
}

It should be noted, though, that you should only use this to send a message to the original sender. Calling a function directly on the actor could cause all sorts of terrible things to happen!

I actually just read about this in Programming in Scala today, so if you want to look up more about it, I highly recommend the book.

msiebert
  • 45
  • 5