A few of us at Rally have started learning Scala. As you can imagine, when learning a new language there are bumps along the road to enlightenment. My first bump while learning Scala was around how Scala determines return type. Can you spot the error?

object Example {
  def main(args: Array[String]) {
    val (a, b) = bad
  }

  def bad {
    ("foo", 2)
  }
}

This code will not compile. The compiler gives an error like:

error: constructor cannot be instantiated to expected type;
found : (T1, T2)
required: Unit
val (a, b) = bad

Hmm… Oh Sh&@T. I forgot the =. If a method doesn’t explicitly define a return type, then an equal sign must be placed after the parameter list in order for the Scala compiler to fill in the return type blank. If you neglect to type an equal sign then the compiler assumes the method returns a generic Unit type. Below you can see the fixed code.

object Example {
  def main(args: Array[String]) {
    val (a, b) = good
  }

  def good = {
    ("foo", 2)
  }
}