Scala Language Pattern Matching Pattern binder (@)


The @ sign binds a variable to a name during a pattern match. The bound variable can either be the entire matched object or part of the matched object:

sealed trait Shape
case class Rectangle(height: Int, width: Int) extends Shape
case class Circle(radius: Int) extends Shape
case object Point extends Shape

(Circle(5): Shape) match {
  case Rectangle(h, w) => s"rectangle, $h x $w."
  case Circle(r) if r > 9 => s"large circle"
  case c @ Circle(_) => s"small circle: ${c.radius}"  // Whole matched object is bound to c
  case Point => "point"

> res0: String = small circle: 5

The bound identifier can be used in conditional filters. Thus:

case Circle(r) if r > 9 => s"large circle"

can be written as:

case c @ Circle(_) if c.radius > 9 => s"large circle"

The name can be bound to only a part of the matched pattern:

Seq(Some(1), Some(2), None) match {
  // Only the first element of the matched sequence is bound to the name 'c'
  case Seq(c @ Some(1), _*) => head
  case _ => None

> res0: Option[Int] = Some(1)