你可以这样做:
def apply(cmd : Command) = {
cmd match {
case c: ValuesCommand with KeysCommand => c.doSomething()
}
}
当你有一个类(例如这里的 ValKey
)既扩展了 ValuesCommand
又扩展了 KeysCommand
,那么你也会拥有类似以下的东西:
class ValKey extends ValuesCommand with KeysCommand`
编辑(您的评论):
我无法想象在这种情况下您需要像 ValuesCommand 或 KeysCommand
这样的东西。您可以阅读 @Randall Schulz 评论中的链接,以了解如何获取OR。
让我们假设您已经有了OR(v),就像链接中描述的那样。
case c: ValuesCommand v KeysCommand => //soo.. what is c?
现在你仍然需要对c进行模式匹配,以找出它是什么类型的命令。(很可能)
因此最终你仍可以直接这样做:
cmd match {
case vc: ValuesCommand => vc.doSomething()
case kc: KeysCommand => kc.doSomehtingElse()
}
编辑2:
如果你想在cmd
上调用你的accept方法,只有当它是ValuesCommand
或KeysCommand
时,你可以这样做:
cmd match {
case _: ValuesCommand | _: KeysCommand => accept(cmd)
}
我猜这样比较DRY
cmd match {
case vc: ValuesCommand => accept(cmd)
case kc: KeysCommand => accept(cmd)
}
ValuesCommand
和KeysCommand
中覆盖(或抽象覆盖)doSomething
方法?这样你就不需要执行模式匹配了。 - maks