use*_*078 3 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.
}
Run Code Online (Sandbox Code Playgroud)
这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.
}
Run Code Online (Sandbox Code Playgroud)
这简直太丑了.有什么建议?
试试这个:
case person: Manager with Investor => // ...
Run Code Online (Sandbox Code Playgroud)
with 用于您可能想要表达类型交集的其他场景,例如在类型绑定中:
def processGenericManagerInvestor[T <: Manager with Investor](person: T): T = // ...
Run Code Online (Sandbox Code Playgroud)
顺便说一句 - 不是这是推荐的做法,但是 - 你也可以像这样测试它: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
}
Run Code Online (Sandbox Code Playgroud)