在模式匹配中,我可以按原样使用匹配的模式吗?

时间:2014-11-22 22:47:18

标签: scala pattern-matching

case first :: rest => first match {
      case Heading(_,_) => buildPairsAcc(rest, acc, ???)
      case Paragraph(_) // ... other cases

而不是 ??? 我想使用匹配的Heading对象。可以在不重复构造函数的情况下完成,还是需要不同的构造?

1 个答案:

答案 0 :(得分:4)

如果我理解你的问题,你想在???的地方使用标题本身,可以使用@模式完成:

case first :: rest => first match {
      case head @ Heading(_,_) => buildPairsAcc(rest, acc, head)
      case Paragraph(_) // ... other cases

请注意,这可用于模式匹配的所有内容,包括列表:

case lst @ head::tail => // do stuff with lst head and tail
相关问题