彻底的模式匹配仅基于类型

时间:2012-11-01 09:55:33

标签: scala pattern-matching

我有一个密封的三个案例类。斯卡拉会告诉我这场比赛是否详尽无遗(我猜不是)?

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)
}

有没有更好的方式像纯粹基于类型这样派遣?

1 个答案:

答案 0 :(得分: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中的任何一个:

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