2

My linters always complain when I don't have a default case in pattern matching in Scala. However, often the default case is artificial and my programs can never actually reach that case.

As an example, consider the following program:

scala> val x = 1
x: Int = 1

scala> x match {
     | case 1 => println("yay")
     | case _ => println("nay")
     | }
yay

It is clear that the bottom case is in fact dead code here, however, my linter will still complain about it. On the other hand, I very much understand the gut feeling that matching on integers and not covering all cases feel dangerous, but in this case it's clearly irrational.

Should I simply delete the default case here and suppress the linter warning to get some peace of mind?

edit: Please see https://www.codacy.com/app/hejfelix/Frase/issues?bid=2858415&filters=W3siaWQiOiJDYXRlZ29yeSIsInZhbHVlcyI6WyJFcnJvciBQcm9uZSJdfV0= for a more detailed view on the number of cases where Codacy asks for default cases.

pedrorijo91
  • 7,635
  • 9
  • 44
  • 82
Felix
  • 8,385
  • 10
  • 40
  • 59

1 Answers1

0

in the example case, an if-else would solve the problem. I don't know your real cases, but maybe if-elses are also applicable

In some other cases, probably is just the linter that it's not powerful enough to understand the default case is not needed. (btw, which one are you using?)

pedrorijo91
  • 7,635
  • 9
  • 44
  • 82
  • I am actually doing an open source project, so Codacy is a free option for me: https://www.codacy.com/app/hejfelix/Frase/dashboard Very happy with the stuff it does. At work I'm also using ScalaStyle. *edit* Also, codacy and travis seem to play quite nicely with each other, especially when you throw in scoverage. – Felix Apr 23 '16 at 12:58
  • To comment on your suggestion, I almost exclusively use pattern matching on case classes to distinguish between different shapes of e.g. Abstract Syntax Trees. There, I would feel extremely handicapped using if/else because I would have to inspect the types explicitly + manually extracting fields etc. Furthermore, I would hope that the compiler does a better job of optimizing my match cases than I would do using if/else myself. – Felix Apr 23 '16 at 13:01