Scala Common Pitfalls

by Stephane Micheloud, August 2009

[Home]
[Back]

In this article we present several programming pitfalls Scala users may fall into.

Procedures

Scala supports special syntax for procedures (see SLS 4.6.3):

Here is a declaration and a definition of a procedure named write:
trait Writer {
  def write(str: String)
}
object Terminal extends Writer {
  def write(str: String) { println(str) }
}
The code above is implicitly completed to the following code:
trait Writer {
  def write(str: String): Unit
}
object Terminal extends Writer {
  def write(str: String): Unit = { println(str) }
}
Using the equals sign without a return type may produce an unexpected result:
object unitvalue extends Application {
  def twice1(x: Int) { 2 * x } // procedure
  def twice2(x: Int) = { 2 * x } // function

  println(twice1(3)) // prints "()"
  println(twice2(3)) // prints "6"
}

Newlines

Scala is a line-oriented language where statements may be terminated by semicolons or newlines (see SLS 1.2).

Omitting one of semicolons in the code below will eg. generate a compiler error.

object semicolons extends App {
  println(1); // [1]
  {
    println(2)
  }
  val i = 3; // [2]
  {
    println(i)
  }
}

The compiler aborts with the error message error: Unit does not take parameters in case [1] and error: Int(3) does not take parameters in case [2].

Variable Patterns

The rules for pattern matching further distinguish between variable identifiers, which start with a lower case letter, and constant identifiers, which do not.

object varpats extends App {
  var liftID = 22
  var doorID = 35
  def test1(id: Int, n: Int): String = {
    (id, n) match {
      case (liftID, n) => "case 1: "+id
      case _ => "case _: "+id
    }
  }
  def test2(id: Int, n: Int): String = {
    val LiftID = liftID
    (id, n) match {
      case (LiftID, n) => "case 1: "+id
      case _ => "case _: "+id
    }
  }
  println("[test1] "+test1(doorID, 3))
  println("[test2] "+test2(doorID, 3))
}
[test1] case 1: 35
[test2] case _: 35

References

  1. The Scala Language Specification (SLS), Version 2.8
    Martin Odersky
    LAMP/EPFL, November 2010

About the Author

Stephane's Picture
Stéphane Micheloud is a senior software engineer. He holds a Ph.D in computer science from EPFL and a M.Sc in computer science from ETHZ. At EPFL he worked on distributed programming and advanced compiler techniques and participated for over six years to the Scala project. Previously he was professor in computer science at HES-SO // Valais in Sierre, Switzerland.
[Top]

Other Articles