The Scala compiler can often infer return types for methods, but there are some circumstances where it’s required to specify the return type. Recursive methods, for example, require a return type to be specified.
I notice that sometimes I get the error message “overloaded method (methodname) requires return type”, but it’s not a general rule that return types must always be specified for overloaded methods (I have examples where I don’t get this error).
When exactly is it required to specify a return type, for methods in general and specifically for overloaded methods?
The Chapter 2. Type Less, Do More of the Programming Scala book mentions:
Example:
Basically, specifying the return type can be a good practice even though Scala can infer it.
Randall Schulz comments:
And since you may want to expose the minimal interface in your return type (see for instance this SO question), this kind of inference might get in the way.
And about the last scenario (“When the inferred return type would be more general than you intended”), Ken Bloom adds:
(The faulty code which triggers a “more general than expected return type was:
, which I incorrectly interpreted and List[Any] because returning an empty List, but Ken called it out: