Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to systematically avoid unsafe pattern matching in Scala?

Consider the following broken function:

def sum (list : Seq[Int]) : Int = list match {
  case Nil => 0
  case head :: tail => head + sum(tail)
}

Here, the function was supposed to work with a List[Int], but was refactored to accept Seq[Int] instead, thus becoming broken without the compiler noticing.

This gaping hole in Scala's incomplete pattern match detection makes it next to useless.

I want to have a way of systematically detecting such problems. Specifically, I'd like the compiler to emit an error/warning on every instanceof-guided pattern match, i.e. I only want to allow pattern matches on sealed hierarchies and on custom matchers.

Are there existing compiler options/plugins for doing conservative (as opposed to arbitrary) checks of pattern matching safety?

like image 337
Rotsor Avatar asked Jan 18 '12 14:01

Rotsor


1 Answers

Have a look at this answer by M. Odersky.

Summary

Checks on matches of non-sealed hierarchies are doable, not trivial and not (yet) implemented.

like image 152
ziggystar Avatar answered Oct 25 '22 02:10

ziggystar