因为sealed 不具有传递性,所以我不清楚缺少编译错误是否是错误。
我注意到在match 表达式中添加另一个大小写会导致编译器发出“无法访问代码”警告。这是我修改后的代码:
#!/usr/bin/env scala
Demo.main(args)
sealed trait Hierarchy {
sealed trait Expr
}
trait If {
this: Hierarchy =>
case class If(cond: Expr, yes: Expr, no: Expr) extends Expr
}
trait Word {
this: Hierarchy =>
case class Word(name: String) extends Expr
}
object SimpleExpr extends Hierarchy with If with Word
//object OtherExpr extends Hierarchy with If with Integer
object Demo extends App {
import SimpleExpr._
def func(expr: Expr) = expr match {
case If(cond, yes, no) => cond
// compiler should emit warning
case Word(name) => printf("word[%s]\n",name)
}
func(Word("yo!"))
}
这是我运行它时得到的结果:
warning: unreachable code
case Word(name) => printf("word[%s]\n",name)
one warning found
word[yo!]
警告不正确,unreachable 代码正在执行中。
当case Word 行被注释掉时,我得到的是:
scala.MatchError: Word(yo!) (of class Main$$anon$1$Word$Word)
at Main$$anon$1$Demo$.func(demo.sc:21)
但是,以下内容确实会发出所需的警告:
#!/usr/bin/env scala
Demo.main(args)
sealed trait Expr
case class Word(name: String) extends Expr
case class If(cond: Expr, yes: Expr, no: Expr) extends Expr
trait Hierarchy
trait IfExpr {
this: Hierarchy =>
}
trait WordExpr {
this: Hierarchy =>
}
object SimpleExpr extends Hierarchy with IfExpr with WordExpr
//object OtherExpr extends Hierarchy with If with Integer
object Demo extends App {
import SimpleExpr._
def func(expr: Expr) = expr match {
case If(cond, yes, no) => cond
// compiler should emit warning
// case Word(name) => printf("word[%s]\n",name)
}
// func(Word("yo!"))
}
这是我收到的警告:
demo.sc:22: warning: match may not be exhaustive.
It would fail on the following input: Word(_)
def func(expr: Expr) = expr match {
^