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
def describe(e: Expr): String = e match {
case Number(_) => “a number” case Var(_) => “a variable”
}
You will get a compiler warning like the following:
warning: match is not exhaustive! missing combination UnOp missing combination BinOp
def describe(e: Expr): String = e match {
case Number(_) => “a number” case Var(_) => “a variable”
case _ => throw new RuntimeException // Should not happen }
That works, but it is not ideal. You will probably not be very happy that you were forced to add code that will never be executed (or so you think), just to make the compiler shut up.
A more lightweight alternative is to add an @unchecked annotation to the selector expression of the match.
def describe(e: Expr): String = (e: @unchecked) match {
case Number(_) => “a number”
case Var(_) => “a variable” }