捕获部分函数的参数

时间:2017-06-22 11:32:33

标签: scala

我正在尝试调试Scala程序(这是一个build.sbt,但问题并不特别针对sbt),我需要为某个sbt设置提供部分功能。部分函数的值如下所示

{
  case Regex1(a,b,c) =>
  case Regex2(d,e,f) =>
  ...
}

部分功能没有做我想要的,所以我想调试它。因为我不确切知道传入的内容,我想捕获传递给部分函数的值,但我不知道该怎么做。

我可以在部分函数的开头添加case a => println(a),但这会破坏整个函数。

3 个答案:

答案 0 :(得分:2)

你可以这样做:

val print: PartialFunction[InputType, InputType] = { case i => println(i); i }
print andThen {
  case Regex1(a,b,c) => ...
  case ...
}

答案 1 :(得分:0)

我终于想出了怎么做。它不是很优雅,所以如果有人知道更好的方法,请添加另一个答案!

解决方案是将部分函数显式创建为值:

val result = new PartialFunction[InputType,ResultType] {
  def apply(value: InputType) = {
    println("input is: " + value) // Yay, I captured the value
    value match {
      // Same as above
    }
  }
  def isDefinedAt(value: InputType) = true
}
result

答案 2 :(得分:0)

另一种选择是匹配所有,并添加另一个匹配实际工作:

{
  case value => {
    println(value)
    value match {
      // the original partial function
      ...
      // you might need to add a catch-all that
      // does nothing or returns a default value
      case _ => None
    }
  }
}