From brain driven development
It turns out, that every Function you’ll ever define in Scala, will
become an instance of an Implementation which will feature a certain
Function Trait.There is a whole bunch of that Function Traits, ranging from Function1 up to
Function22.Since Functions are Objects in Scala and Scala is a statically typed
language, it has to provide an appropriate type for every Function
which comes with a different number of arguments. If you define a
Function with two arguments, the compiler picks Function2 as the
underlying type.
Also, from Michael Froh’s blog
You need to make FunctionN classes for each number of parameters that
you want? Yes, but you define the classes once and then you use them
forever, or ideally they’re already defined in a library (e.g.
Functional Java defines classes F, F2, …, F8, and the Scala standard
library defines classes Function1, …, Function22)
So we have a list of function traits (Scala), and a list of interfaces (Functional-java) to enable us to have first class funtions.
I am trying to understand exactly why this is the case. I know, in Java for example, when I write a method say,
public int add(int a, int b){
return a + b;
}
That I cannot go ahead and write
add(3,4,5);
( error would be something like : method add cannot be applied to give types )
We simply have to define an interface/trait for functions with different parameters, because of static typing?
3
One does have to implement functions as first-class objects in Scala somehow, no? When the programmer e.g. assigns a function literal to a variable, that variable must get some value at runtime that represents the function in a type-safe way. The implementers of Scala have chosen to do it the way the FunctionN traits work. So, all the syntax for functions in Scala is essentially just syntactic sugar for that implementation. Each function of e.g. some type (A, B C) => D
becomes an object that has type Function3[A,B,C,D]
at runtime and thus, among other things, implements a method apply(p1: A, p2: B, p3: C): D
.
Applying the function is syntactic sugar for calling the apply method etc.
Also, this is how Java can interoperate with Scala functions.