Over a million developers have joined DZone.

How are functions treated in Scala?

DZone 's Guide to

How are functions treated in Scala?

· Java Zone ·
Free Resource

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

1. trait Function1[A,B]{
2.    def apply(x: A): B
3. }

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:

1. (x: Int) => x * x

when expanded per the above definition below is the structure:

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

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:

1. val f = (x:Int) => x*x
2. f(2)
3. val f = new Function1[Int,Int]{
4.   def apply(x: Int): Int = x * x 
5. }
6. f.apply(2)
1. 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.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}