Scala pattern matching syntax

I recently played with the scala pattern, and I was wondering if there is a way to create an extractor inside the case statement. The following code works, but first you must define the extractor and assign it to 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, it is something like this:

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

EDIT: If any of the scala team reads this: would it be possible to implement this?

+6
source share
2 answers

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

The frame should be followed by a template. The Scala language specification shows BNF patterns in section 8.1. The grammar of the templates is quite powerful, but in fact it is just a template, method calls or constructors are not allowed there.

+5
source

I had a similar problem and solved it as follows:

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

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

0
source

Source: https://habr.com/ru/post/892027/


All Articles