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?
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
Using if expressions in case statements First, another example of how to match ranges of numbers: i match { case a if 0 to 9 contains a => println("0-9 range: " + a) case b if 10 to 19 contains b => println("10-19 range: " + b) case c if 20 to 29 contains c => println("20-29 range: " + c) case _ => println("Hmmm...") }
A regular expression is a pattern of text that consists of ordinary characters, for example, letters a through z, and special characters. Character(s) Matches in searched string. pattern.
Adding the case keyword causes the compiler to add a number of useful features automatically. The keyword suggests an association with case expressions in pattern matching. First, the compiler automatically converts the constructor arguments into immutable fields (vals). The val keyword is optional.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With