scala 模式匹配 `@` 符号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20748858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pattern Matching `@` Symbol
提问by Kevin Meredith
Given this Personcase class:
鉴于这个Person案例类:
scala> case class Person(name: String, age: Int) {}
defined class Person
... and this instance
...还有这个例子
scala> val b = Person("Kevin", 100)
b: Person = Person(Kevin,100)
Is there a reason to prefer this code (with @)
是否有理由更喜欢此代码(带有@)
scala> b match {
| case p @ Person(_, age) => println("age")
| case _ => println("none")
| }
age
... over the following?
... 以下?
scala> b match {
| case Person(_, age) => println("age")
| case _ => println("none")
| }
age
Perhaps I'm missing the meaning/power of @?
也许我错过了@?
回答by wheaties
You only include the @when you want to also deal with the object itself. Hence:
您只包括@何时还想处理对象本身。因此:
that match{
case p @ Person(_, age) if p != bill => age
case Person(_, age) => age - 15
case _ => println("Not a person")
}
Otherwise, there's no real point in including it.
否则,包含它没有任何意义。
回答by Praveen L
Regarding the comments for the above answer.
关于上述答案的评论。
Consider this case class.
考虑这个案例类。
case class Employee(name: String, id: Int, technology: String)
while doing pattern matching.
在进行模式匹配时。
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**

