Scala Higher Order Function

In scala, when a function accepts another function as an argument or returns a function as an output, is called Higher order function. Let’s understand this with examples.

Example1

Map is the good example for understanding higher order function. To demonstrate how this accepts a function as argument, we will create a function which will multiply the same number twice and then we will pass that function into map.

We can also pass the anonymous function to perform the same task as above. For that, we can create an anonymous function as given below.

Anonymous function: x => x * x

It will give the same output.

Example2

Now, Let’s create a user defined higher order function which accepts a function as an arguments and returns nothing.

We will pass the below function as an argument, which itself accepts a String parameter and returns string parameter.

Next, define the function that matches the signature with above function which accept string parameter and return string parameter.

val myname = (name: String) => s”$name”

Now, Create a higher order function which takes 2 arguments and print the message as output of the function.

We can call the function as given below.

Now, let’s combine the full code and see the output.

Example3

Let’s create a function that returns an anonymous function, assign that to a new function and then call that new function.

Define an anonymous function that takes a String as an argument and returns String.

Let’s create a function that returns the above anonymous function from its body.

Now, We will call that function and assign it to a new function. New function will make another call with desired message to be printed.

Let’s combine the whole code and see the output.

Scala Currying Function
Scala - Recursive Functions
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *