什么是' @'运营商在Scala做什么?

时间:2014-03-29 20:47:06

标签: scala akka

我正在查看Akka代码库中的一些Scala代码,下面的代码片段负责处理异常。

override val supervisorStrategy =
OneForOneStrategy(loggingEnabled = false) {
  case e @ InvalidAssociation(localAddress, remoteAddress, reason) ⇒
    log.warning("Tried to associate with unreachable remote address [{}]. " +
      "Address is now gated for {} ms, all messages to this address will be delivered to dead letters. Reason: {}",
      remoteAddress, settings.RetryGateClosedFor.toMillis, reason.getMessage)
    endpoints.markAsFailed(sender(), Deadline.now + settings.RetryGateClosedFor)
    AddressTerminatedTopic(context.system).publish(AddressTerminated(remoteAddress))
    Stop

  case ShutDownAssociation(localAddress, remoteAddress, _) ⇒
    log.debug("Remote system with address [{}] has shut down. " +
      "Address is now gated for {} ms, all messages to this address will be delivered to dead letters.",
      remoteAddress, settings.RetryGateClosedFor.toMillis)
    endpoints.markAsFailed(sender(), Deadline.now + settings.RetryGateClosedFor)
    AddressTerminatedTopic(context.system).publish(AddressTerminated(remoteAddress))
    Stop

第3行的代码,case e @ InvalidAssociation - InvalidAssociation确实是一种异常类型,但为什么e @是必需的,它有什么作用?

1 个答案:

答案 0 :(得分:4)

它是 bind 运算符。它允许您为一些复杂的模式匹配值分配标识符,因此 - 例如 - 当对案例类进行模式匹配时,您可以引用该案例类的字段以及案例类实例本身:

case class Record(intField: Int, stringField: String)

val something: Any = ...
something match {
   case entireInstance @ Record(intField, stringField) =>
       println(s"$entireInstance has fields $intField and $stringField")
}