Nested functions

Why will you require a nested functions support in your programming language? Most of the time, we want to maintain our methods to be a few lines and avoid overly large functions. A typical solution for this in Java would be to define all these small functions on a class level, but any other method could easily refer and access them even though they are helper methods. The situation is different in Scala, so you can use define functions inside each other, and this way, prevent any external access to these functions:

def sum(vector: List[Int]): Int = {
// Nested helper method (won't be accessed from outside this function
def helper(acc: Int, remaining: List[Int]): Int = remaining match {
case Nil => acc
case _ => helper(acc + remaining.head, remaining.tail)
}
// Call the nested method
helper(0, vector)
}

We are not expecting you to understand these code snippets, which show the difference between Scala and Java.

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

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