模式匹配 `@` 符号 [英] Pattern Matching `@` Symbol
本文介绍了模式匹配 `@` 符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定这个 Person
案例类:
scala> case class Person(name: String, age: Int) {}
defined class Person
...还有这个实例
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
...以下?
scala> b match {
| case Person(_, age) => println("age")
| case _ => println("none")
| }
age
也许我错过了 @
的意义/力量?
Perhaps I'm missing the meaning/power of @
?
推荐答案
当您还想处理对象本身时,您只需要包含 @
.因此:
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.
这篇关于模式匹配 `@` 符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文