且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scala @运算符

更新时间:2023-11-10 20:18:52

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

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.