Search code examples
scalapattern-matchingakkacase-class

Scala capture object reference while still using extractors


Is there any way to make this:

// I'm using akka, perhaps there's a magic variable inside receive I can use
def receive = {
  case Message(channel, data, sender) => {
    // do stuff with channel, data, sender
    // Oops, I want to reuse message, so I have to build a new one
    foo ! Message(channel, data, sender)
  }
}

Into something like this:

def receive = {
  case x: Message(channel, data, sender) => {
    // do stuff with channel, data, sender
    // Now I want to reuse message
    foo ! x
  }
}

Solution

  • Use @ to also capture the full object.

    case x @ Message(channel, data, sender) => {
        // do stuff with channel, data, sender
        foo ! x
    }