Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pattern matching syntax

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?

like image 756
Kim Stebel Avatar asked Jul 05 '11 12:07

Kim Stebel


People also ask

Does Scala have pattern matching?

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.

How do you use match function in Scala?

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...") }

What is pattern matching syntax?

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.

How do you write a match case in Scala?

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.


1 Answers

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.

like image 126
kassens Avatar answered Oct 02 '22 11:10

kassens