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..

pedrorijo91
  • 7,635
  • 9
  • 44
  • 82

2 Answers2

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.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
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

Community
  • 1
  • 1
kikulikov
  • 2,512
  • 4
  • 29
  • 45