Ravi Ravi - 10 months ago 49
Scala Question

Scala - syntax is difficult to understand

I am learning Scala and Akka, I am basically java programer. I am seeing variety of syntax, but few I am not able to understand. Can please help me:

case class ProcessStringMsg(string: String)
case class StringProcessedMsg(words: Integer)

class StringCounterActor extends Actor {
def receive = {
case ProcessStringMsg(string) => {
val wordsInLine = string.split(" ").length
sender ! StringProcessedMsg(wordsInLine)
case _ => println("Error: message not recognized")

Here what is the meaning of
sender ! StringProcessedMsg(wordsInLine)

Could you please explain.

Answer Source

foo.bar(baz) can be written as foo bar baz in Scala. Notice that we are omitting . here. . is optional in this case (case where method takes only one parameter)

sender ! StringProcessedMsg(wordsInLine) can be understood as sender.!(StringProcessedMsg(wordsInLine))

But With respect to implementation

sender ! StringProcessedMsg(wordsInLine) is akin to sender.tell(StringProcessedMsg(wordsInLine))

taken from akka codebase

final def tell(msg: Any, sender: ActorRef): Unit = this.!(msg)(sender)

override def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit = 
  actorCell.sendMessage(message, sender)