Scala has a feature to define a function in the body of another function. The scope of these functions is the declaring function only. That is, they are not accessible from anywhere else in the code. These functions are called local functions. Sometimes we need a set of small functions to define a complete functionality. Those functions are not contextual in other places. In that scenario, local functions come into the picture. Let’s take an example. object GCD {
def gcdList(list:List[Int]):Int = {
Local function
def gcd(x:Int, y:Int):Int =
if (y == 0) x else gcd(y, x%y)
list match {
case Nil => 0
case h::t => gcd(h, gcdList(t))
}
} Here, the recursive function gcd() inside gcdList() is a local function. Expect to come across this popular question in Spark Scala interviews.