6

I've been playing with scala pattern matching recently and was wondering whether there is a way to create an extractor inside of the case statement. The following code works, but you have to define the extractor first and assign it to a val:

val Extr = "(.*)".r
"test" match {
  case Extr(str) => println(str)
}

What I would like to do, or what I would like someone to confirm is impossible, is something like this:

"test" match {
  case ("(.*)".r)(str) => println(str)
}

EDIT: In case anyone from the scala team is reading this: Would it be feasible to implement this?

3
  • +1 for the suggestion! This would be useful indeed in other cases. Commented Jul 5, 2011 at 13:16
  • @JPP: Indeed. The case I was originally thinking of was that of or and and as library functions to build complex extractors from simpler ones. Commented Jul 5, 2011 at 13:39
  • See also stackoverflow.com/questions/2411573/… Commented Jul 5, 2011 at 14:13

2 Answers 2

5

Unfortunately it is not possible and I see no way to simplify your first example.

The case statement has to be followed by a Pattern. The Scala Language Specification shows the BNF of patterns in section 8.1. The grammar of patterns is quite powerful, but is really just a pattern, no method calls or constructors are allowed there.

Sign up to request clarification or add additional context in comments.

Comments

0

I had a similar problem and i solved it like this:

case x if x.matches("regex") => foo(x)

I don't know if this is exactly what you want, but it works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.