escargot agile
escargot agile

Reputation: 22389

In pattern matching, can I use the matched pattern as is?

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

Instead of the ??? I'd like to use the matched Heading object. Can it be done without repeating the constructor, or do I need a different construct?

Upvotes: 0

Views: 49

Answers (1)

Electric Coffee
Electric Coffee

Reputation: 12124

If I understand your question correctly, you want to use the heading itself on ???'s place, this can be done using the @ pattern:

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

Note that this can be used on everything that'll pattern match, including lists:

case lst @ head::tail => // do stuff with lst head and tail

Upvotes: 4

Related Questions