What does Scala's @ operator do?
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)
You can easily extract the content:
o match {
case Some(x) => println(x)
case None =>
}
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.