圖案裝訂器()

@ 符號在模式匹配期間將變數繫結到名稱。繫結變數可以是整個匹配物件,也可以是匹配物件的一部分:

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

繫結識別符號可用於條件過濾器。從而:

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

可以寫成:

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

名稱只能繫結到匹配模式的一部分:

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)