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.

    val f = (x:Int) => x + 10
    //res0: Int = 20              

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.

    val f = new Function1[Int, Int] {
        def apply(x: Int): Int = x + 10
    //res1: Int = 20                 

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:

Scala Function Basics

Start learning Scala functions from the basics and become an expert.

Learning Journal

Kafka Core Concepts

Learn Apache Kafka core concepts and build a solid foundation on Apache Kafka.

Learning Journal

Scala Functions

Scala is a functional programming language. Functions are the building blocks in Scala.

Learning Journal

Pure Functions

What are pure functions and side effects. Start learning functional programming.

Learning Journal

Spark in Google cloud

Learn How to Install Hadoop and Spark in Google Cloud in just 2 minuts.

Learning Journal