Because sealed
isn't transitive, it's not clear to me whether the lack of a compile error is a bug or not.
I noticed that adding another case to the match
expression causes the compiler to issue an "unreachable code" warning. Here's my modified version of your code:
#!/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!"))
}
Here's what I get when I run it:
warning: unreachable code
case Word(name) => printf("word[%s]\n",name)
one warning found
word[yo!]
The warning is incorrect, the unreachable
code is being executed.
When the case Word
line is commented out, here's what I get:
scala.MatchError: Word(yo!) (of class Main$$anon$1$Word$Word)
at Main$$anon$1$Demo$.func(demo.sc:21)
The following, however, does issue the desired warning:
#!/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!"))
}
Here's the warning I get:
demo.sc:22: warning: match may not be exhaustive.
It would fail on the following input: Word(_)
def func(expr: Expr) = expr match {
^