Anonymous Function


A standard function has a name, a list of parameters, a return type, and a body. If you do not give a name to a function, it is an anonymous function.
Let's take a simple example in Scala.

The first line defines a standard function. The second line defines the same function without a name. So the second line defines an anonymous function. If you compare the syntax for an anonymous Scala function with a standard Scala function, you may notice a small difference. A normal function uses = symbol whereas an Anonymous function uses => symbol. Some people call it an anonymous function whereas others may refer it as lambda. However, anonymous function and lambda are two different names for the same thing. You might be wondering how to call this function if it does not have a name. You can assign it to a variable.


Now, you can call it using the variable.

However, that is not the real purpose of an anonymous function. If we wanted to assign it to a variable and call it later, why do we create an anonymous function? What's wrong with the named function? I mean, a named function or an anonymous function assigned to a variable is the almost same thing. So the big question is this.

What is the purpose of an anonymous function?

Why would you want to create an anonymous function? The answer is simple. There might be scenarios where you want to create an inline function for a one-time usage. Giving a name to a function does not make any sense if you do not want to use it anywhere else. In those scenarios, creating an anonymous function is quite convenient. Let me show you an example. You have already seen the below example earlier.


In the above code, we create two local functions and then return them later. The only purpose of creating those local functions is to return them. We can do the same thing using anonymous functions.

The above code is much precise, straightforward and clean. Instead of defining two local functions and then returning them later, I simply use anonymous function, right at the place where it is needed. This kind of code is more convenient to write and easy to understand. In this example, both the anonymous functions have same input parameter list. So, we can apply another shortcut and move the input parameter list outside the body.

You may have several such scenarios where you just want to create a function and use it right there. Anonymous functions are there to allow you to do that.
Keep reading for more interesting functional concepts.

Read More

Pure Functions | Referential Transparency | Benefits of pure functions | First class functions | Higher order function | Anonymous functions | Immutability | Tail Recursion | Expressions in Scala | Lazy Evaluations | Pattern Matching | Closures

By Prashant Pandey -



You will also like: