【问题标题】:What does the '@' operator do in Scala? [duplicate]'@' 运算符在 Scala 中的作用是什么? [复制]
【发布时间】:2014-05-09 07:46:03
【问题描述】:

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

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 @ 是必要的,它有什么作用?

【问题讨论】:

  • @DonRoby 在我查看时没有出现在任何搜索结果中,无论如何。
  • 搜索“@”之类的内容有些困难。完全可以理解!
  • @DonRoby 完全同意!
  • 如果您使用引号,则可以正确搜索符号 - 例如搜索 scala "@" 有效,但搜索 scala @ 无效。我只是偶然发现了这一点,但事后看来,search help

标签: scala akka


【解决方案1】:

这是一个 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")
}

【讨论】:

  • 啊哈!这是有道理的——因此,我可以将别名绑定到整个案例对象本身,而不仅仅是模式匹配案例对象的内部。谢谢!
  • 在案例类中处理 Options 时也很有帮助,例如:f @ Foo(Some(id), _, _) 当您只想匹配具有定义 ID 的 Foos 时。
猜你喜欢
  • 1970-01-01
  • 2017-04-24
  • 2012-03-30
  • 2016-02-20
  • 2016-07-24
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多