This page is no longer maintained — Please continue to the home page at

A Tour of Scala: Nested Functions

In Scala it is possible to nest function definitions. The following object provides a filter function for extracting values from a list of integers that are below a threshold value:

object FilterTest extends Application {
  def filter(xs: List[Int], threshold: Int) = {
    def process(ys: List[Int]): List[Int] =
      if (ys.isEmpty) ys
      else if (ys.head < threshold) ys.head :: process(ys.tail)
      else process(ys.tail)
  println(filter(List(1, 9, 2, 8, 3, 7, 4), 5))

Note that the nested function process refers to variable threshold defined in the outer scope as a parameter value of filter.

The output of this program is:



Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland