Scala @ 运算符 [英] Scala @ operator

查看:35
本文介绍了Scala @ 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 的@ 运算符有什么作用?

What does Scala's @ operator do?

例如,在博客文章 Scala 中的形式语言处理,第 2 部分 有一个类似这样的内容

For example, in the blog post Formal Language Processing in Scala, Part 2 there is a something like this

case x @ Some(Nil) => x

推荐答案

它使人们能够将匹配的模式绑定到变量.例如,请考虑以下事项:

It enables one to bind a matched pattern to a variable. Consider the following, for instance:

val o: Option[Int] = Some(2)

您可以轻松提取内容:

o match {
  case Some(x) => println(x)
  case None =>
}

但是,如果您想要的不是 Some内容,而是选项本身,该怎么办?这将通过以下方式实现:

But what if you wanted not the content of Some, but the option itself? That would be accomplished with this:

o match {
  case x @ Some(_) => println(x)
  case None =>
}

请注意,@ 可以在任何级别使用,而不仅仅是在匹配的顶级.

Note that @ can be used at any level, not just at the top level of the matching.

这篇关于Scala @ 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆