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 ...

Get Scala Functional Programming Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.