Local functions – hiding and biding their time
Java classes have private methods. These private methods hide implementation details. Scala supports this way of hiding but also allows us to nest functions by making it easy to create local functions. We have already seen an example earlier when we looked at recursion. Our count
function hid implementation details by nesting the work horse function:
def count(list: List[Int]): Int = { // the facade @tailrec def countIt(l: List[Int], acc: Int): Int = l match { // The work horse // omitting body... } countIt(list, 0) // call the real thing }
As good kids, we should hide the innards of how we really implemented the counting. The caller is not really interested in whether we are using tail recursion and the accumulator idiom.
The local function has a scope of its own. Let's try the following commands:
scala> def f(n: Int) = { | val k = (y: Int) => y < n // 1 | k | } f: (n: Int)Int => Boolean scala...