【发布时间】:2011-05-02 15:55:55
【问题描述】:
我正在使用 Scala match/case 语句来匹配给定 java 类的接口。我希望能够检查一个类是否实现了接口的组合。我似乎可以让它工作的唯一方法是使用嵌套的 match/case 语句,这看起来很丑。
假设我有一个 PersonImpl 对象,它实现了 Person、Manager 和 Investor。我想看看 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.
}
这简直丑陋。有什么建议吗?
【问题讨论】:
-
case person: Manager with Investor应该可以工作。当你对这些你说只是Manager的对象调用Investor方法时会发生什么? -
如果您能接受答案或告诉我们您想了解的有关此主题的其他信息,那就太好了。