Scala @ operator

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.

Leave a Comment