Anonymous functions

Sometimes in your code, you don't want to define a function prior to its usage, maybe because you will use it in one place. In functional programming, there's a type of function that is very suitable to this situation. It's called an anonymous function. Let's demonstrate the use of anonymous functions using the previous example of transferring money:

def TransferMoney(money: Double, bankFee: Double => Double): Double = {
money + bankFee(money)
}

Now, let's call the TransferMoney() method with some real value as follows:

 TransferMoney(100, (amount: Double) => amount * 0.05)
Lambda expression:
As already stated, Scala supports first-class functions, which means functions can be expressed in function-literal syntax as well; functions can be represented by objects, called function values. Try the following expression, it creates a successor function for integers:
scala> var apply = (x:Int) => x+1
apply: Int => Int = <function1>
The apply variable is now a function that can be used in the usual way as follows:
scala> var x = apply(7)
x: Int = 8
What we have done here is simply use the core of a function: the argument list followed by the function arrow and the body of the function. This one is not black magic but a full-fledged function, only without a given name--that is, anonymous. If you define a function this way, there will be no way to refer to that function afterward and hence you couldn't call that function afterward because without a name it's an anonymous one. Also, we have a so-called lambda expression! It's just the pure, anonymous definition of a function.

The output of the preceding code is as follows:

105.0

So, in the previous example instead of declaring a separate callback function, we passed an anonymous function directly and it did the same job just like the bankFee function. You can also omit the type in the anonymous function and it will be directly inferred based on the passed argument like this:

TransferMoney(100, amount => amount * 0.05)

The output of the preceding code is as follows:

105.0

Let's demonstrate the previous example on the Scala shell as shown in the following screenshot:

Figure 6: Use of the anonymous function in Scala

Some programming languages that have functional support use the name lambda function instead of anonymous function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.132.33