1

我有三个密封的案例类。Scala 会告诉我这场比赛是否详尽(我猜不是)?

value match {
  case a: A => methodThatNeedsA(a)
  case b: B => methodThatNeedsB(b)
  case c: C => methodThatNeedsC(c)
}

我可以执行以下操作,我知道这将是详尽无遗的 - 但由于我不需要分解表达式,它看起来非常混乱:

value match {
  case a @ A(_) => methodThatNeedsA(a)
  case b @ B(_, _) => methodThatNeedsB(b)
  case c @ C(_, _, _) => methodThatNeedsC(c)
}

有没有更好的方法来像这样纯粹基于类型进行调度?

4

1 回答 1

4

我刚刚测试了你的代码:

sealed trait Base
case class A(x: Int) extends Base
case class B(x: Int, y: Int) extends Base
case class C(x: Int, y: Int, z: Int) extends Base

如果我删除case模式匹配中的三个 s 中的任何一个:

value match {
    case a: A => methodThatNeedsA(a)
    case b: B => methodThatNeedsB(b)
    //case c: C => methodThatNeedsC(c)

}

编译器发出警告:

warning: match is not exhaustive!
missing combination              C
于 2012-11-01T10:03:29.147 回答