Scala中的Extractor对象和类

问题描述 投票:2回答:1

我正在为函数表达式编写提取器对象。这是它的样子:

object FunctionTemplate2 {
  private final val pattern = Pattern.compile("^(.+?)\\((.+?)\\,(.+?)\\)")
  //e.g. foo(1, "str_arg")
  def unapply(functionCallExpression: String): Option[(String, String, String)] = {
      //parse expression and extract
  }
}

我可以提取如下:

"foo(1, \"str_arg\")" match {
  case FunctionTemplate2("foo", first, second) =>
    println(s"$first,$second")
}

但这并不像它可能那么可爱。我想有类似的东西:

case FunctionTemplate2("foo")(first, second) =>
  println(s"$first,$second")

像咖喱提取器。所以我尝试了这个:

case class Function2Extractor(fooName: String){
  private final val pattern = Pattern.compile("^(.+?)\\((.+?)\\,(.+?)\\)")
  println("creating")
  def unapply(functionCallExpression: String): Option[(String, String, String)] = 
    //parse and extract as before
}

但它不起作用:

"foo(1, \"str_arg\")" match {
  case Function2Extractor("foo")(first, second) =>
    println(s"$first,$second")
}

有没有办法在Scala中执行此操作?

scala pattern-matching
1个回答
1
投票

您可以通过在Scala工具集中使用一些实用程序来简单地使用它

请注意在匹配情况下如何使用pattern

Scala REPL

scala> val pattern = "^(.+?)\\((.+?)\\,(.+?)\\)".r
pattern: scala.util.matching.Regex = ^(.+?)\((.+?)\,(.+?)\)

scala> "foo(1, \"str_arg\")" match  { case pattern(x, y, z) => println(s"$x $y $z")}
foo 1  "str_arg"
© www.soinside.com 2019 - 2024. All rights reserved.