Scala pattern matching syntax

泄露秘密 提交于 2019-12-21 12:59:22

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/6583011/scala-pattern-matching-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!