O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required