Gregor Raýman Gregor Raýman -4 years ago 142
Scala Question

How to suppress the "match may not be exhaustive" warning in Scala?

I am currently implementing a small internally used utility that imports data from a set of Excel files to our application. Based on the type of the Excel cell, I decide how to treat the data. The Excel file can contain only string, numeric and Boolean cells, if any other cell is encountered, the program is free to crash at run-time.

Now Scala is correctly warning me that the match on the cell type is not exhaustive, the cells can have the type of blank, formula, error...

Is there a way how to suppress the warning, except the obvious one?:

t match {
case STRING => ???
case NUMERIC => ???
case BOOLEAN => ???
case _ => throw new MatchError() // redundant, just to suppress the compile time warning
}

Answer Source

You could use the unchecked annotation:

(t: @unchecked) match {
  case STRING => ???
  case NUMERIC => ???
  case BOOLEAN => ???
}

As others have mentioned, you should avoid using it and instead choose your types accordingly to avoid such warnings (e.g. by using sealed traits). If, however, you find yourself unable to do so, and you have some kind of invariant that guarantees that your type is always one of the given types, using @unchecked solves your problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download