Scala : Compiler emits no warning when pattern matching against a sealed trait -
here snippet. when pattern matching, compiler emits no warning. know workaround ?
i compiler emit warning when forget case when pattern matching against simpleexpr.expr
, otherexpr.expr
. construct allows me factor nodes common both expression trees (like if
)
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 if word //object otherexpr extends hierarchy if integer object demo extends app { import simpleexpr._ def func(expr: expr) = expr match { case if(cond, yes, no) => cond // compiler should emit warning } }
because sealed
isn't transitive, it's not clear me whether lack of compile error bug or not.
i noticed adding case match
expression causes compiler issue "unreachable code" warning. here's modified version of 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 if word //object otherexpr extends hierarchy if 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 when run it:
warning: unreachable code case word(name) => printf("word[%s]\n",name) 1 warning found word[yo!]
the warning incorrect, unreachable
code being executed.
when case word
line commented out, here's get:
scala.matcherror: word(yo!) (of class main$$anon$1$word$word) @ main$$anon$1$demo$.func(demo.sc:21)
the following, however, issue 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 ifexpr wordexpr //object otherexpr extends hierarchy if 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 warning get:
demo.sc:22: warning: match may not exhaustive. fail on following input: word(_) def func(expr: expr) = expr match { ^
Comments
Post a Comment