Scala模式活页夹(@)
示例
所述@符号模式匹配期间结合到名称的变量。绑定变量可以是整个匹配对象或匹配对象的一部分:
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}" //整个匹配对象绑定到c case Point => "point" }
>res0:String=smallcircle:5
绑定标识符可以在条件过滤器中使用。从而:
case Circle(r) if r > 9 => s"large circle"
可以写成:
case c @ Circle(_) ifc.radius> 9 => s"large circle"
该名称只能绑定到匹配模式的一部分:
Seq(Some(1), Some(2), None) match { //仅匹配序列的第一个元素绑定到名称“c” case Seq(c @ Some(1), _*) => head case _ => None }
>res0:Option[Int]=Some(1)