When to use the equals sign in a Scala method declaration?

I actually disagree pretty strongly with Daniel. I think the non-equal syntax should never be used. If your method is being exposed as an API and you’re worried about accidentally returning the wrong type, add an explicit type annotation:

object HelloWorld {
  def main(args: Array[String]): Unit = {
    println("Hello!")
    123
  }
}

The non-equal syntax is shorter and might look “cleaner”, but I think it just adds the possibility of confusion. I have sometimes forgotten to add an equal sign and believed my method was returning a value when actually it was returning Unit. Because the non-equal and equal-with-inferred-type syntaxes are so visually similar, it’s easy to miss this problem.

Even though it costs me a little more work, I prefer the explicit type annotations when they matter (namely, exposed interfaces).

Leave a Comment