1

Is there a difference between the two following..

scala> def foo() = {}
foo: ()Unit

scala> def foo() {}
foo: ()Unit

They seem to be the same.
Is there a reason both are supported?

Sean Connolly
  • 5,692
  • 7
  • 37
  • 74

1 Answers1

6
def foo() {}

is equivalent to (and enforces)

def foo(): Unit = {}

while

def foo() = {}

will apply type infering to determine the result type from the body of the method.

So, with the first two options, Unit is the only allowed return type, while in the third, the return type depends on the implementation.

Leo
  • 37,640
  • 8
  • 75
  • 100
  • Aaah, fantastic explanation. I didn't know return types could be inferred, thanks Mef! – Sean Connolly Feb 15 '13 at 00:07
  • It's one of the many awesome things of the Scala language :-) It is worth noting that for methods/functions, at least those of your public API, the return type should still be displayed to be nice to readers of your code/API. – adelbertc Feb 15 '13 at 00:09
  • 1
    @SeanConnolly: Indeed, in most circumstances return types can be inferred by the compiler (the cannot if it is directly recursive). But it is often not a good idea to rely on it. There are two reasons not rely on type inference for methods: 1) Explicit result types have documentation value; 2) Inferred types may be narrower or more complex than you like. An example of (2) is returning a `HashMap`. You probably don't want your API contract to specify such a specific type and absent an explicit return type annotation, you'll be tied to that concrete type lest you make a breaking change. – Randall Schulz Feb 15 '13 at 00:16
  • Good point @RandallSchulz, cheers! – Sean Connolly Feb 15 '13 at 00:28