Scala @运算符 [英] Scala @ operator

查看:90
本文介绍了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 content ,而是该选项本身,该怎么办?可以这样实现:

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天全站免登陆