views:

373

answers:

5
+6  Q: 

Scala @ operator

What does scala @ operator do?

For example at this page there is a something like this

case x @ Some(Nil) => x
A: 

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) }
Mitch Blevins
Not top level only.
Daniel
+3  A: 

When pattern matching variable @ pattern binds variable to the value matched by pattern if the pattern matches. In this case that means that the value of x will be Some(Nil) in that case-clause.

sepp2k
+2  A: 

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

oxbow_lakes
Damn the inability of iPhones to render a backtick!
oxbow_lakes
+11  A: 

@ 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.

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)
retronym
+11  A: 

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.

Daniel
Where in the documentation would I find that answer? I have a feeling there's other good stuff buried there as well. :)
Jim Barrows
@Jim Scala Reference, 8.1. 8.12, specifically, though I don't know where the "as usual" there came from -- and 8.12 only speak of regular expression pattern (`_*`). But maybe this has been clarified on a newer version of the spec.
Daniel
I would add that you would probably not use `@` with `Some(_)`, but rather if you wanted to match on the contents of the `Some`, but still refer to the Some itself, e.g. `case x @ Some(7) => println(x)`. As I interpret it `case x @ Some(_)` is just a more verbose version of `case x: Some`.
Theo