Scala @ 运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2359014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:59:03  来源:igfitidea点击:

Scala @ operator

scalaoperators

提问by lowercase

What does Scala's @ operator do?

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

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

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

case x @ Some(Nil) => x

回答by Daniel C. Sobral

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

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

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

You can easily extract the content:

您可以轻松提取内容:

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

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

但是,如果你想没有内容Some,但选择本身?这将通过以下方式实现:

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

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

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

回答by retronym

@can be used to bind a name to a successfully matched pattern, or subpattern. Patterns can be used in pattern matching, the left hand side of the <-in for comprehensions, and in destructuring assigments.

@可用于将名称绑定到成功匹配的模式或子模式。模式可用于模式匹配、in 的左侧<-用于理解,以及解构赋值。

scala> val d@(c@Some(a), Some(b)) = (Some(1), Some(2))
d: (Some[Int], Some[Int]) = (Some(1),Some(2))
c: Some[Int] = Some(1)
a: Int = 1
b: Int = 2

scala> (Some(1), Some(2)) match { case d@(c@Some(a), Some(b)) => println(a, b, c, d) }
(1,2,Some(1),(Some(1),Some(2)))

scala> for (x@Some(y) <- Seq(None, Some(1))) println(x, y)
(Some(1),1)

scala> val List(x, xs @ _*) = List(1, 2, 3) 
x: Int = 1
xs: Seq[Int] = List(2, 3)

回答by sepp2k

When pattern matching variable @ patternbinds variableto the value matched by patternif the pattern matches. In this case that means that the value of xwill be Some(Nil)in that case-clause.

当模式匹配variable @ pattern结合可变由匹配的值模式,如果模式匹配。在这种情况下,这意味着 的值xSome(Nil)在 case-clause 中。

回答by Mitch Blevins

Allows you to match the top-level of a pattern. Example:

允许您匹配模式的顶级。例子:

case x @ "three" => assert(x.equals("three"))
case x @ Some("three") => assert(x.get.equals("three")))
case x @ List("one", "two", "three") => for (element <- x) { println(element) }

回答by oxbow_lakes

It sets the value of xto the pattern which matches. In your example, xwould therefore be Some(Nil)(as you could determine from a call to println)

它将 的值设置为x匹配的模式。在您的示例中,x因此将是Some(Nil)(正如您可以从对println的调用中确定的那样)