Scala match / case statement when mapping Java interfaces

I use the Scala operator match/caseto match the interface of this Java class. I want to be able to check if a class implements a combination of interfaces. The only way to get this to work is to use nested expressions match/casethat seem ugly.

Suppose I have a PersonImpl object that implements Person, Manager, and Investor. I want to see if PersonImpl implements both Manager and Investor. I should be able to do the following:

person match {
  case person: (Manager, Investor) =>
    // do something, the person is both a manager and an investor
  case person: Manager =>
    // do something, the person is only a manager
  case person: Investor =>
    // do something, the person is only an investor
  case _ =>
    // person is neither, error out.
}

case person: (Manager, Investor)just doesn't work. To make it work, I have to do the following, which seems ugly.

person match {
  case person: Manager = {
    person match {
      case person: Investor =>
        // do something, the person is both a manager and investor
      case _ =>
        // do something, the person is only a manager
    }
  case person: Investor =>
    // do something, the person is only an investor.
  case _ =>
    // person is neither, error out.
}

It is just ugly. Any suggestions?

+3
source share
1 answer

:

case person: Manager with Investor => // ...

with , , . :

def processGenericManagerInvestor[T <: Manager with Investor](person: T): T  = // ...

, , , - : if (person.isInstanceOf[Manager] && person.isInstanceOf[Investor]) ....


: :

trait A
trait B
class C

def printInfo(a: Any) = println(a match {
  case _: A with B => "A with B"
  case _: A => "A"
  case _: B => "B"
  case _ => "unknown"
})

def main(args: Array[String]) {
  printInfo(new C)               // prints unknown
  printInfo(new C with A)        // prints A
  printInfo(new C with B)        // prints B
  printInfo(new C with A with B) // prints A with B
  printInfo(new C with B with A) // prints A with B
}
+8

All Articles