模式匹配`@`符号

时间:2013-12-23 18:06:55

标签: scala pattern-matching

鉴于此Person案例类:

scala> case class Person(name: String, age: Int) {}
defined class Person

...和这个实例

scala> val b = Person("Kevin", 100)
b: Person = Person(Kevin,100)

是否有理由更喜欢此代码(使用@

scala> b match {
     |    case p @ Person(_, age) => println("age")
     |    case _ => println("none")
     | }
age

...以下?

scala> b match {
     |    case Person(_, age) => println("age")
     |    case _ => println("none")
     | }
age

也许我错过了@的意思/力量?

2 个答案:

答案 0 :(得分:89)

当您还要处理对象本身时,只包括@。因此:

that match{
  case p @ Person(_, age) if p != bill => age
  case Person(_, age) => age - 15
  case _ => println("Not a person")
}

否则,将它包括在内并没有真正的意义。

答案 1 :(得分:6)

关于上述答案的评论。

考虑这个案例类。

case class Employee(name: String, id: Int, technology: String)

在进行模式匹配时。

case e @ Employee(_, _, "scala") => e.name // matching for employees with only scala technology ... it works

case x: Employee => x.name // It also works

case e: Employee(_, _, "scala") => e.name // matching for employees with only scala technology ... **wont't work**