Scala Compiler Quirks

Recently I have been dabbling with scala a bit. As it happens I found a few quirks in the compiler.

So does the following bit of code compiler and, if so, what does it print?

object Example {
    val x = y
    val y = true
 
    def main(args: Array[String]) {
        print(x);
    }
}

Yes you’ll get false and that is plain wrong. In my opinion a compiler error would have been fine and ideally, as there are no cycles it would have just printed true.

Another major selling point of scala is it’s pattern matching mechanism. A very convenient feature is the compiler’s ability to print a warning, if the cases provided are not exhaustive. A very simple case of such a non-exhaustive match is this:

object CaseExample {
      def main(args: Array[String]) {
          val b = args.length == 1
          b match {
              case true => print("True")
          }
 
      }
  }

Unfortunately the compiler doesn’t complain at all. After some googling I came across SI-3111. My own problem was slighty, but only slightly more complicated. I matched tupels of Options against Some and None.

We have been bitten by both problems, that lead to really subtle bugs. This is really unfortunate, because the compiler can do a lot more in a language like scala. The first problem gets even caught by javac.

A third shortcoming of scala can be easily fixed. Set the tab size to four spaces and your code will
look a lot more structured.

To me it seems like the scala compiler unnessarily discredits the idea of strong static checks by a somehwat quirky implementation.

2 Comments

  1. toni says:

    Man, imagine how more you could do with ruby..
    No I am joking not in the mood to suggest ruby these days with all the mess that bundle, rvm are creating.

    I had hopes in scala, even if it’s not liked over here (the main argument is that you can’t write idiomatic code, cos you can be either functional or OO or a mix of the two). But these bugs are a bit scary.

    Just wait for java 10.. they will port one day the scala features there

  2. Sean Flanigan says:

    Two years later, it looks like the pattern matching bug has been fixed (“warning: match may not be exhaustive.”).

    The forward reference example still returns false with scala-2.10.2, apparently by design, with only an optional _runtime_ check. See http://stackoverflow.com/questions/12184997/scala-and-forward-references/12185918#12185918

Leave a Reply