[ad_1]
UPDATE: as of Scala-2.10, using equals sign is preferred. Old answer:
Methods which return Unit
should always use the non-equals syntax. This avoids potential mistakes in implementation carrying over into the API. For example, you could have accidentally done something like this:
object HelloWorld {
def main(args: Array[String]) = {
println("Hello!")
123
}
}
Trivial example of course, but you can see how this might be a problem. Because the last expression does not return Unit
, the method itself will have a return type other than Unit
. This is exposed in the public API, and might cause other problems down the road. With the non-equals syntax, it doesn’t matter what the last expression is, Scala fixes the return type as Unit
.
It’s also two characters cleaner. 🙂 I also tend to think that the non-equals syntax makes the code just a little easier to read. It is more obvious that the method in question returns Unit
rather than some useful value.
On a related note, there is an analogous syntax for abstract methods:
trait Foo {
def bar(s: String)
}
The method bar
has signature String=>Unit
. Scala does this when you omit the type annotation on an abstract member. Once again, this is cleaner, and (I think) easier to read.
[ad_2]