1.

What is a local function?

Answer»

SCALA has a feature to define a function in the body of another function. The scope of these functions are 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.



Discussion

No Comment Found