As mentioned, higher-order functions also support returning a function as a result. Let's demonstrate this by an example:
def transferMoney(money: Double) = {
if (money > 1000)
(money: Double) => "Dear customer we are going to add the following
amount as Fee: "+money * 0.05
else
(money: Double) => "Dear customer we are going to add the following
amount as Fee: "+money * 0.1
}
val returnedFunction = TransferMoney(1500)
returnedFunction(1500)
The preceding code segment will produce the following output:
Dear customer, we are going to add the following amount as Fee: 75.0
Let's run the previous example as shown in the following screenshot; it shows how to use the function as a return value:
Figure 7: Function as a return value
The complete code of the preceding example can be seen as follows:
package com.chapter3.ScalaFP
object FunctionAsReturnValue {
def transferMoney(money: Double) = {
if (money > 1000)
(money: Double) => "Dear customer, we are going to add following
amount as Fee: " + money * 0.05
else
(money: Double) => "Dear customer, we are going to add following
amount as Fee: " + money * 0.1
}
def main(args: Array[String]) {
val returnedFunction = transferMoney(1500.0)
println(returnedFunction(1500)) //Prints Dear customer, we are
going to add following amount as Fee: 75.0
}
}
The output of the preceding code is as follows:
Dear customer, we are going to add following amount as Fee: 75.0
Now before stopping our discussion on HFO, let's see a real-life example, that is, currying using HFO.