Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How are functions treated in Scala?

DZone's Guide to

How are functions treated in Scala?

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:

Published at DZone with permission of Abhishek Jain, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}