Scala Function Literals

Let's start with the meaning of the term literal in computer science.

A literal is a notation for representing a fixed value in source code.

We have been using literals for a long time to assign fixed values to different data types. The code below shows some examples.

                                        
    val s = "Hello World!"
    val l = 5
    //By default, it is an Integer, but I can specify the data type
    val l: Long = 5
    //Another alternative for enforcing the data type.
    val l = 5:Long              
                                    

The first line of the above codes uses a string literal. The second line uses an integer literal. Now, let's talk about the functional programming paradigm.
One of the basic ideas of functional programming is that the functions are the first class citizens. They are like values. So, whatever you can do with values, you should be able to do it with the functions. Like any other value, we can assign functions to a variable. We can pass them as a parameter, and we can return them from a higher order function. We can also create values using a literal as shown in the above example.
Can we create a function using a literal?
If we can create a string value using a string literal, we must be able to create a function value using a function literal.


Function literal Syntax

Here is the syntax for creating a function literal.

                                        
    ([<parameterName> : <type> [, ....]])  =>  {   
            function body 
            return [expr] 
        } : [return type]
        //Function literal example
        val f = (x:Int) => { x + 5 }
        //Compare it with String literal
        val s = "Hello World!"
        //You can enforce the return type
        val f = (x:Int) => { x + 5 }:Int                 
                                    

You can compare it with the standard function syntax that we start with the keyword def.
You will notice three differences.

  1. We do not have a function identifier (function name)
  2. A right arrow symbol replaces the equal to sign
  3. The return type moved to the end

It is exactly same as we created a value earlier. Instead of using a string literal, we use a function literal. In the example above, I skipped the return type for the function value because Scala automatically infers the return type. However, you can enforce it by putting it in the end as shown in the later part of the code. You might be wondering that when we created a long value, we specified the type annotation in the front. Can we do the same with function literals? Refer the below code.

                                        
    val l: Long = 5
    //Can we do the same with the function literal?
    val f: Int => Int = (x:Int) => { x + 5 }                 
                                    

The above example shows that we can specify the function type in the front. However, you must remember the difference between the front place and the tail position.

  1. The tail position defines a return type
  2. The front place defines the function type

The function type includes the input type and the return type both separated by a => symbol. The input type comes before the => symbol, and hence we have an Int there because the function takes a single integer as input.
The return type comes after the => symbol, and hence we have an Int there as well because the function returns an integer.
However, you do not need to specify the function type or the return type because Scala should be able to infer that automatically.
Here is another example.

                                        
    val myFun:(Int, String) => String = (x:Int, s:String) => { s + x + s }:String
    //Recomended syntax
    val myFun = (x:Int, s:String) =>  s + x + s                 
                                    

The myFun is a val. The code before the = symbol is the function type and the code after the = symbol is the function literal. However, the recommendation is to avoid the optional parts.
So we remove everything starting with the : and go up to the = symbol. We also removed the return type from the tail position.
We learned some other optional parts in an earlier article such as a semicolon, return keyword, curly braces. All of those rules are also applicable to function literals. Hence, we removed the curly braces as well.
That is all about function literals. Some people call them anonymous functions, and others refer them as lambda functions. However, these are three names for the same thing in Scala. You might wonder with the following question.
Where do we use function literals?
Most of the time, you will use function literal with higher order functions. I mean, either you will be passing it to a higher order function or returning it. I have covered it with suitable examples in a dedicated section about Higher Order functions.
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 Variable length arguments

How do you create a variable length argument in Scala? Why would you need it?

Learning Journal

Referential Transparency

Referential Transparency is an easy method to verify the purity of a function.

Learning Journal

Local Functions

How do you implement private methods in a functional programming language.

Learning Journal

Statements and Expressions

Statements and Expressions in Scala. How are they different?

Learning Journal

Lazy Evaluations

Evaluate the expression now vs evaluate it for the first use. Strict vs Lazy?

Learning Journal