The idea of functionN in Scala / Functionaljava

Posted by Luke Murphy on Programmers See other posts from Programmers or by Luke Murphy
Published on 2012-11-24T14:43:12Z Indexed on 2012/11/24 17:17 UTC
Read the original article Hit count: 212

Filed under:
|
|

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?

© Programmers or respective owner

Related posts about scala

Related posts about functions