Tuesday, December 24, 2013

Functions as Objects

How are functions treated in Scala?
Are functions objects in Scala?

Functions values are treated as objects in Scala.
Any function definition of type A => B is equivalent to type Function1[A,B] and this can be expanded with below definition

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

So such traits actually supported by Scala. Function1, Function2,... Function21 in scala package. With such support Scala does support Function definition with 22 parameters.

Anonymous Functions

Expanding the above conversation to see how Anonymous Functions are supported.
For example:

(x: Int) => x * x

when expanded per the above definition below is the structure:

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

The above definition suggest similar to anonymous class structure provided by Java.

Function Calls

Above discussion provides an understanding of function definition treatment in Scala, but how about function calls. Funtion calls maps to apply method as describe in the structure above.

Lets expand this discussion in terms of below definition which declares an anonymous function and further a call is made to the function:

val f = (x:Int) => x*x
f(2)

val f = new Function1[Int,Int]{
  def apply(x: Int): Int = x * x  
}
f.apply(2)


def f(x: Int): Int = f(x)
out of this (x: Int) => f(x) is treated as anonymous function and expanded by Scala in a similar way discussed above. This translation of a name f is termed as 'eta - expansion' in lamda calculas.

No comments:

Post a Comment