模式匹配中的绑定变量

模式匹配中的绑定变量

使用 @ 将匹配的结果绑定为变量,p@Person("Bob", 12, a@Address("1 hello world", "2 hello world", "CN")),这样在后面就可以使用变量a和p。

case class Address(street: String, city: String, country: String)

case class Person(name: String, age: Int, address: Address)

val alice = Person("Alice", 12, Address("1 hello world", "2 hello world", "CN"))
val bob = Person("Bob", 12, Address("1 hello world", "2 hello world", "CN"))
val charlie = Person("Charlie", 12, Address("1 hello world", "2 hello world", "CN"))

for (person <- Seq(alice, bob, charlie)) {
  person match {
    case p@Person("Alice", 12, Address(_, "2 hello world", _)) =>
      println(s"hi alice,$p")
    case p@Person("Bob", 12, a@Address("1 hello world", "2 hello world", "CN")) =>
      println(s"hi ${p.name},age ${p.age},in ${a.city}")
    case p@Person(name, age, _) =>
      println(s"who are you? $age year-old person named $name? $p")
  }
}

见模式匹配之case class:http://my.oschina.net/xinxingegeya/blog/617354

注意和下面的模式匹配的区别,

/**
  * Seq集合中的所有元素都能匹配到
  */
for (person <- Seq(alice, bob, charlie)) {
  person match {
    case p: Person => println(s"person=$p")
  }
}

这种类型的模式匹配只能匹配类型,将匹配的结果绑定为变量p,可以在后面直接使用变量,也可以像像下面这样,获取变量p中的属性字段,

/**
  * Seq集合中的所有元素都能匹配到
  */
for (person <- Seq(alice, bob, charlie)) {
  person match {
    case p: Person => println(s"person=${p.name}")
  }
}

========END========

你可能感兴趣的:(模式匹配中的绑定变量)