scala - 如何模式匹配扩展多个特征的对象?

标签 scala pattern-matching traits

我有一个父类(super class) Command ,许多不同的子类从 Command 扩展,同时也可以扩展这些特性中的一个或多个 ValuesCommandKeysCommandMembersCommand 和许多其他特性。

现在我想模式匹配同时扩展 CommandValuesCommandKeysCommand 的所有实现。

这是我想要实现的一些 伪代码 :

def apply(cmd : Command) = {
  cmd match {
    case c:(ValuesCommand && KeysCommand) => c.doSomething()
  }
}

我可以回退以匹配第一个特征并嵌套第二个 match 。但我真的不需要它,看起来很糟糕。

最佳答案

你可以这样做:

def apply(cmd : Command) = {
  cmd match {
    case c: ValuesCommand with KeysCommand => c.doSomething()
  }
}

当你有一个既扩展 ValKeyValuesCommand 的类(例如这里的 KeysCommand)时,你也有类似的东西
class ValKey extends ValuesCommand with KeysCommand`

编辑(您的评论):

在这种情况下,我无法想象您想要 ValuesCommand or 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 方法的场景,仅当它是 ValuesCommandKeysCommand 时,您可以执行以下操作:
cmd match {
  case _: ValuesCommand | _: KeysCommand => accept(cmd)
}

我想,这比
cmd match {
  case vc: ValuesCommand => accept(cmd)
  case kc: KeysCommand   => accept(cmd)
}

关于scala - 如何模式匹配扩展多个特征的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23479186/

相关文章:

error-handling - 字符串 io::Errors 是如何创建的

scala - 在 Scala 中动态选择记录器的实现

rust - 特征对象和特征的直接实现者的特征实现

regex - RegEx模式可在这些情况下限制破折号

scala - 在存在更高种类类型的情况下,如何控制模式匹配中绑定(bind)变量的推断类型

scala - 解构 Scalaz <**>

scala - 在运行时获取 Scala 变量名

regex - 如果原始列表不匹配,如何知道列表中字符串的变体(例如缩写)是否与另一个列表匹配?

scala - Akka Streams - 如何在图表中保留辅助接收器的物化值

java - 如何通过反射从 Scala 访问 Java 静态成员?