模式匹配中的绑定变量

模式匹配中的绑定变量

使用 @ 将匹配的结果绑定为变量,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========

转载于:https://my.oschina.net/xinxingegeya/blog/636235

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值