Search code examples
scalapattern-matchingcase-class

scala - how to bind a variable name in a multiple pattern matching clause


I want to pattern match using the same "case" to 2 different case classes but I am getting an error that the binded variable name is already in use:

for instance this:

statement match {
  case FirstCase(a,b) => {lots of logic using "a" and "b"}
  case SecondCase( obj : FirstCase, somethingElse) => {same logic as above}
  ...
  ...
}

I'd love to re-use the same logic :

statement match {
  case obj: FirstCase | SecondCase( obj : FirstCase, somethingElse) => 
{lots of logic using "obj.a" and "obj.b"}
  ...
  ...
}

But I am getting a compile error "obj is already defined in scope"

Is it possible to "re-use" the name of the binded object?


Solution

  • You can use helper method:

      def hlp(a: TypeOfA, b: TypeOfB) = ???
    
      statement match {
        case FirstCase(a, b) => hlp(a, b)
        case SecondCase(FirstCase(a, b), somethingElse) => hlp(a, b)
      }