Scala Function Values


The function value is another confusing term among various Scala concepts. A beginner is often confused with a function literal and a function value. In this post, I will try to eliminate that confusion with suitable examples.
We already learned about function literals in the prevous article.
The following code represents a function literal.

Do you know what happens when you create a function literal?
When you compile the above code, Scala will instantiate an object for this literal using a predefined function class and assign it to the value f.
Here is an equivalent code that Scala generates internally.


Typically, we use the function literal in two possible ways.

  1. Assign it to a value as we do in the first example
  2. Pass it to a higher-order function or return it from a higher-order function

In both cases, Scala compiler will instantiate an object for the function literal, and assign it to a value.
So the function value is an object whereas a function literal is a source code for it. The literal is like a body of a class definition, and the value is an object instantiated using that class body.
In the above code example, f is a function value whereas the code written after the = symbol is a function literal.
Continue reading for more concepts.

Read More

Basics of Scala functions | Function Literals in Scala | Function values | Local Functions | Variable length argument | Default values and named arguments | Scala Placeholder syntax | Higher Order functions | Partially applied functions | Function currying

By Prashant Pandey -



You will also like: