daniel kullmann
daniel kullmann

Reputation: 14013

Capture argument to partial function

I am trying to debug a Scala program (this is a build.sbt, but the question is not particular for sbt), where I need to give a partial function for a certain sbt setting. The value for the partial function looks like this

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

The partial function does not do what I want, so I wanted to debug it. Because I don't know exactly what is passed in, I want to capture the value that is passed into the partial function, but I don't know how to do that.

I could add a case a => println(a) at the beginning of the partial function, but this breaks the whole function.

Upvotes: 0

Views: 158

Answers (3)

daniel kullmann
daniel kullmann

Reputation: 14013

Another option would be to match all, and add another match that does the actual work:

{
  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
    }
  }
}

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170713

You can do this:

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

Upvotes: 2

daniel kullmann
daniel kullmann

Reputation: 14013

I finally figured out how to do it. It is not very elegant, so if anyone knows of a better way, please add another answer!

The solution is to create the partial function explicitly as value:

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

Upvotes: 0

Related Questions