case语句的变量绑定(p @ T)

假设以下场景:你需要从对象中提取值,但你又想将一个变量赋给该对象的整体。该怎么做呢?
我们来对前文中匹配Person 类的属性的实例做以下修改。

 1     case class Address(street: String, city: String, country: String)
 2     case class Person(name: String, age: Int, address: Address)
 3 
 4     val alice = Person("Alice", 25, Address("1 Scala Lane", "Chicago", "USA"))
 5     val bob = Person("Bob", 29, Address("2 Java Ave.", "Miami", "USA"))
 6     val charlie = Person("Charlie", 32, Address("3 Python Ct.", "Boston", "USA"))
 7 
 8     for (person <- Seq(alice, bob, charlie)) {
 9       person match {
10         case p@Person("Alice", 25, address) => println(s"Hi Alice! $p")
11         case p@Person("Bob", 29, a@Address(street, city, country)) =>
12           println(s"Hi ${p.name}! age ${p.age}, in ${a.city}")
13         case p@Person(name, age, _) =>
14           println(s"Who are you, $age year-old person named $name? $p")
15       }
16     }
17   }

p @ …的语法将整个 Person 类的实例赋值给了变量 p,类似地,a @ …也将整个 Address实例赋值给了变量。以下为修改版本的实例输出。(为适应排版做了格式化。)

 

 

记住,如果不需要从Person 实例中提取属性值,我们只要写为p: Person => …就可以了。

posted @ 2022-08-02 17:49  linbo.yang  阅读(345)  评论(0编辑  收藏  举报