Corresponds to "offset": run the same code for more than one case class?

advertisements

I have a function in Scala that matches different case classes, but executes the same code on every match. Is there a possibility to “fallthrough”? Or a other nice way to write the code bellow without code duplication and without defining a function?

symbol match {
            case Times(a,b) => //some code using a and b
            case Plus(a,b)  => //same code as above
            case Div(a,b)   => //again same code as above
}

This is a pretty similar too the question "Match "fallthrough": executing same piece of code for more than one case?" with the difference that I'm intressted in matching with case classes.


You could write your own extractor that combines the three cases and turns them into a tuple:

  object BinOp {
    def unapply(op: Op) = op match {
      case Times(a, b) => Some(a, b)
      case Plus(a, b) => Some(a, b)
      case Div(a, b) => Some(a, b)
    }
  }

  symbol match {
    case BinOp(a, b) =>
  }