Sunday, August 3, 2014


Functions in scala are converted into object representations by the scala compiler.

For example:

  def sumOfSquare(squareFn: Int => Int, x: Int) : Int  = {
        var sum = 0;
        for(i: Int <- 1 to x) {
                sum = sum + squareFn(i);
        }
        sum

  }

Note the function argument type squareFn: Int => Int in the above snippet.  The scala compiler converts this function type into a trait type.  The trait for the above function argument type looks like this: 

package scala
trait Function1[A, B] {
       def apply(x: A): B
}

Traits in scala are similar to interface in java. So the above sumOfSquare function will indeed take a trait object as its argument in place of the actual function. Imagine that the compiler converts the above snippet into this code:

  def sumOfSquare(squareFn: Function1[Int, Int], x: Int) : Int  = {
        var sum = 0;
        for(i: Int <- 1 to x) {
                sum = sum + squareFn(i);
        }
        sum

  }

Function1 is predefined trait available under the scala package. Infact, the scala package contains many such traits for functions with varying number of arguments. The above Function1 trait is for a two argument function.

Now, that's about function argument type. How about calling the sumOfSquare function by passing the squareFn value.

sumOfSquare( (x: Int)=>x*x, 5)

Note that sumOfSquare function is called with an anonymous function that is directly passed as argument.  Scala compiler will internally create an object that implements Function1 trait, and will pass that object as an argument. The function calling code above is converted into below code by the compiler.

sumOfSquare ( new Function1[Int, Int] {
                                 def apply(x: Int)  = x * x
                         },  5)

Infact, it is nothing but a shorter representation of trait implementation object that would look like this:

{
 class Anonfunc extends Function1[Int, Int] {
          def apply(x: Int) : Int = x * x
 }
 new Anonfunc
}

Finally the squareFn call from within the sumOfSquares function will be converted into below code by the compiler, which calls the apply method implemented by the Function1 object.

squareFn.apply(i)

Function argument types and their definitions are therefore truly represented by using objects in scala. The language provides syntactic sugar for the users to concisely create function arguments or call functions easily without worrying about the internal details.