Hamy
Hamy

Reputation: 21572

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

Upvotes: 8

Views: 1152

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

Use @ to also capture the full object.

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

Upvotes: 20

Related Questions