0

I was surfing some code examples on akka and I found a particular example that I would like to be sure of the meaning:

def receive: Receive = { case original@Ping(x) => // do stuff case _ => //do stuff }

Ping is a case class used for message in the example. But What's the meaning of that original@ ? Is it the message sender? if so, is there any advantage of this approach over using the sender variable?

Sorry, but I can't give you the link because I can't find it anymore...

Not sure if this Akka thing or just a advanced Scala pattern matching feature that I wasn't aware..

2 Answers 2

3

It is a Scala feature called variable binding. It binds the value being matched on to the variable. You can find more examples here Scala @ operator

3

The easiest way to find out is to try it:

case class Ping(x: Int)

scala> val msg = Ping(10)
msg: Ping = Ping(10)

scala> msg match {
     |    case original @ Ping(x) => {
     |        println("Original: " + original)
     |        println("x: " + x)
     |    }
     |    case _ => println("no match")
     | }
Original: Ping(10) // Printed the entire msg that was matched
x: 10              // Printed just the value x that was matched

So original is equivalent to msg which is Ping(10). The @ symbol lets you assign the entire matched object to an identifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.