Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to see what a wildcard pattern is receiving during a match in Scala?

When doing pattern matching in an Akka or Scala Actor, is there a way to see what the match was NOT (i.e.) what is being evaluated by the wildcard _? Is there a simple way to see which message is being processed from the mailbox that it can't find a match for?

def receive = {
  case A =>
  case B =>
  case C =>
  ...
  case _ =>
    println("what IS the message evaluated?")
}

Thanks,

Bruce

like image 371
Bruce Ferguson Avatar asked Jan 18 '26 03:01

Bruce Ferguson


2 Answers

You can just define variable like this:

def receive = {
  case A =>
  case B =>
  case C =>
  ...
  case msg =>
    println("unsupported message: " + msg)
}

You can even assign names to the messages that you are matching with @:

def receive = {
  case msg @ A => // do someting with `msg`
  ...
}
like image 200
tenshi Avatar answered Jan 19 '26 19:01

tenshi


The "correct" way to do this in Akka is to override the "unhandled"-method, do what you want, and either delegate to the default behavior or replace it.

http://akka.io/api/akka/2.0-M4/#akka.actor.Actor

As for pattern matching in general, just match on anything, and bind it to a name, so you can refer to it:

x match {
  case "foo" => whatever
  case otherwise => //matches anything and binds it to the name "otherwise", use that inside the body of the match
}
like image 27
Viktor Klang Avatar answered Jan 19 '26 20:01

Viktor Klang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!