2011-05-02 30 views
3

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

可以说我有一个PersonImpl对象,它实现了Person,Manager和Investor。我想看看PersonImpl是否实现了经理和投资者。我应该可以做到以下几点:

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

这简直太难看了。有什么建议么?

+0

'情况的人:经理Investor'应该工作。当你对这些对象调用一个'Investor'方法时会发生什么,你说的只是'Manager'? – 2011-05-02 20:14:22

+0

如果您可以接受答案或告诉我们您想知道关于此主题的其他信息,那将是非常好的。 – 2011-05-24 09:42:55

回答

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 
} 
+0

我刚刚测试过案例:经理与投资者,不幸的是它没有工作。它捕获只实施经理的人员以及实施两者的人员。这是一个错误? – user523078 2011-05-02 16:27:57

+0

好笑。我在我的答案中添加了一个简短的例子,对我来说Scala 2.8.1很适合。你正在使用哪个版本? – 2011-05-02 16:33:38

+0

你是对的。我只是运行你的例子,它的工作。在我的情况下,我没有使用traits,因为“class”是一个java并正在实现一个接口,但我认为这不重要。 – user523078 2011-05-02 18:30:06