首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala中的密封类

Scala中的密封类
EN

Stack Overflow用户
提问于 2013-11-08 18:22:15
回答 2查看 1.2K关注 0票数 2

下面是我的代码片段:

代码语言:javascript
复制
sealed abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr
case class UnOp(operator: String, arg: Expr) extends Expr
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr

object CaseClassTest extends App {
    def simplifyExp(xs: Expr): Expr = xs match {
      case UnOp("-",UnOp("-", x)) => x
      case BinOp("+",x,Number(0)) => x
      case BinOp("*",x,Number(1)) => x
    }

    def describe(e: Expr): String = e match {
      case Number(_) => "Number"
      case Var(_) => "Var"
    } 
}

现在,在描述方法中发生的事情,我得到了一个警告:“匹配可能不是详尽无遗的,它将在以下输入上失败: BinOp(_,_, ),UnOp(,_)”。它看起来非常适合我,因为我没有考虑其他测试用例,比如BinOp、UnOp。完美

但是我的问题是为什么def simplifyExp(xs: Expr):Expr没有收到同样的警告呢?有什么东西我遗漏了吗?谢谢

EN

回答 2

Stack Overflow用户

发布于 2013-11-08 18:38:16

对于simplifyExp,您使用提取器组合,我认为编译器不够聪明,无法检测到问题。

显然,下面的代码在运行时使用MatchError失败

代码语言:javascript
复制
CaseClassTest.simplifyExp(Var("toto"))
票数 5
EN

Stack Overflow用户

发布于 2013-11-08 18:38:54

编译器显示一个真正的警告,因为simplifyExp不能处理Expr类型的所有参数。例如,在做:

代码语言:javascript
复制
scala> simplifyExp(new Var("as"))
scala.MatchError: Var(as) (of class Var)
        at .simplifyExp(<console>:22)
        at .<init>(<console>:24)...

类似地,它不能处理BinOp(_, _, _)类型的参数,即接受任何字符串的BinOp、任何左Expr、右Expr。

关于第二个函数,更改声明的顺序,并显示describe的警告:

代码语言:javascript
复制
scala> object CaseClassTest extends App {
    def describe(e: Expr): String = e match {
      case Number(_) => "Number"
      case Var(_) => "Var"
    }

    def simplifyExp(xs: Expr): Expr = xs match {
      case UnOp("-",UnOp("-", x)) => x
      case BinOp("+",x,Number(0)) => x
      case BinOp("*",x,Number(1)) => x
    }

}
<console>:23: warning: match may not be exhaustive.
It would fail on the following inputs: BinOp(_, _, _), UnOp(_, _)
           def describe(e: Expr): String = e match {
                                           ^
defined module CaseClassTest

如果您在上述情况下更正了describe,那么它也将为simplifyExpr显示。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19865923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档