匹配Java接口时的Scala匹配/ case语句

时间:2011-05-02 15:55:56

标签: scala pattern-matching

我正在使用Scala match/case语句来匹配给定java类的接口。我希望能够检查一个类是否实现了接口的组合。我似乎能够使用它的唯一方法是使用嵌套的match/case语句,这些语句看起来很难看。

假设我有一个实现Person,Manager和Investor的PersonImpl对象。我想看看PersonImpl是否实现了Manager和Investor。我应该能够做到以下几点:

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)无效。为了使它工作,我必须做以下看似丑陋。

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

这简直太丑了。有什么建议吗?

1 个答案:

答案 0 :(得分:8)

试试这个:

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
}