匹配 Java 接口时的 Scala match/case 语句
我使用 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.
}
案例人员:(经理,投资者)
不起作用。为了让它工作,我必须做以下看起来丑陋的事情。
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.
}
这简直太丑了。有什么建议吗?
I'm using the Scala match/case
statement to match an interface of a given java class. I want to be able to check if a class implements a combination of interfaces. The only way I can seem to get this to work is to use nested match/case
statements which seems ugly.
Lets say I have a PersonImpl object which 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.
}
The case person: (Manager, Investor)
just doesn't work. In order to get it to work I have to do the following which seem 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.
}
This is just plain ugly. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
with
用于您可能想要表达类型交集的其他场景,例如在类型绑定中:顺便说一句 - 不是推荐的做法,但是— 您也可以像这样测试它:
if (person.isInstanceOf[Manager] && person.isInstanceOf[Investor]) ...
。编辑:这对我来说很有效:
Try this:
with
is used for other scenarios where you might want to express type intersection, e.g. in a type bound:By the way — not that this is recommended practice, but — you can always test it like this as well:
if (person.isInstanceOf[Manager] && person.isInstanceOf[Investor]) ...
.Edit: this works well for me: