Higher Order Functions in Scala

Functions that accept other functions as parameters and/or use functions as return values are known as higher-order functions.

In the below example, safeStringOp() function takes another function f and a String value s and invokes the function f with s as parameter for s != null

package com.scala.test

object TestHigherOrder {

def safeStringOp(s: String, f: String => String) = {
if (s != null) f(s) else s
}

def reverser(s: String) = s.reverse

def main(args: Array[String]) {
println(safeStringOp(null, reverser))
println(safeStringOp(“Gyan”, reverser))
}

}

Output
null
nayG

Function That Returns a Function

The following code declares an Anonymous Function:
(s: String) => {
prefix + ” ” + s
}

We can return that anonymous function from the body of another function as follows:

def addPrefix(prefix: String) = (s: String) => {
prefix + ” ” + s
}

package com.scala.test

object ReturnFuntion {

def addPrefix(prefix: String) = (s: String) => {
prefix + ” ” + s
}
def main(args: Array[String]) {
val prefix = addPrefix(“Gyan”)
println(prefix)
println(prefix(“Mishra”))

}
}

Output
com.scala.test.ReturnFuntion$$$Lambda$1/868693306@682a0b20
Gyan Mishra

Leave a Reply

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