【问题标题】:Exhaustively pattern match based only on the type仅基于类型的详尽模式匹配
【发布时间】:2012-11-01 18:03:29
【问题描述】:

我有三个密封的案例类。 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)
}

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

【问题讨论】:

    标签: scala pattern-matching


    【解决方案1】:

    我刚刚测试了你的代码:

    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
    

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

    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
    

    【讨论】:

    • 哇,好吧 - 我只是假设它无法检查,因为它涉及动态投射!愚蠢的假设。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    相关资源
    最近更新 更多