我最近一直在玩 Scala 模式匹配,想知道是否有办法在 case 语句中创建提取器.以下代码有效,但您必须先定义提取器并将其分配给一个 val:
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) }如果 Scala 团队的任何人正在阅读此内容:实施此内容是否可行?
In case anyone from the scala team is reading this: Would it be feasible to implement this?
推荐答案不幸的是,这是不可能的,我认为没有办法简化您的第一个示例.
Unfortunately it is not possible and I see no way to simplify your first example.
case 语句后面必须跟一个模式.Scala 语言规范在第 8.1 节中显示了模式的 BNF.模式的语法非常强大,但实际上只是一个模式,不允许有方法调用或构造函数.
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.
更多推荐
Scala 模式匹配语法
发布评论