图案装订器()
@
符号在模式匹配期间将变量绑定到名称。绑定变量可以是整个匹配对象,也可以是匹配对象的一部分:
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)