There are many ways functions can be defined in Scala, which leads to confusion about when exactly function parameter types are required. I usually start with the simplest possible definition and work my way down until compiler errors go away. I’d rather actually understand how this works.
For example:
_ + _
(x, y) => x + y
(x: Int, y: Int) => x + y
def sum(x: Int, y: Int) = x + y // as pointed out, this is a method,
// which not a function
Bonus points for a link to the documentation.
Well there are some corner cases like: a recursive method must be explicitly typed, but normally the rule of thumb is as follows: types have to come from somewhere.
Either they come from the reference part:
or from the object part:
does not really matter. (in Scala!)
I know you question is about functions, but here is a similar example to illustrate Scala’s type inference:
EDIT As requested I add the higher-order function case.
can be called like this:
But, this is not a special case. The type of the reference is explicitly mentioned. The following code illustrates a similar example.
This is roughly equivalent to the higher-order function case.