有没有一种方法可以在Scala中查看通配符模式在匹配过程中接收到的内容



在Akka或Scala Actor中进行模式匹配时,有没有一种方法可以查看匹配不是什么(即通配符_正在评估什么)?有没有一种简单的方法可以查看正在处理的邮箱中找不到匹配的邮件?

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

谢谢,

Bruce

您可以这样定义变量:

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

您甚至可以为与@:匹配的消息分配名称

def receive = {
  case msg @ A => // do someting with `msg`
  ...
}

在Akka中执行此操作的"正确"方法是覆盖"未处理"-方法,执行您想要的操作,并委托给默认行为或替换它。

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

至于一般的模式匹配,只需对任何内容进行匹配,并将其绑定到一个名称,这样您就可以引用它:

x match {
  case "foo" => whatever
  case otherwise => //matches anything and binds it to the name "otherwise", use that inside the body of the match
}

最新更新