object LongLines {
  def processFile(filename: String, width: Int) = {
    val source = Source.fromFile(filename)
    for (line <- source.getLines())
      processLine(filename, width, line)
  private def processLine(filename: String, width: Int, line: String) = {
    if (line.length > width)
      println(filename + ": " + line.trim)

LongLines with a private processLine method

To use LongLines from the command line, we’ll create an application that expects the line width as the first command-line argument, and interprets subsequent arguments as filenames:

object FindLongLines {
  def main(args: Array[String]) = {
    val width = args(0).toInt
    for (arg <- args.drop(1))
      LongLines.processFile(arg, width)

Local functions

In Java, your main tool for this purpose is the private method. This private-method approach works in Scala as well, as demonstrated, but Scala offers an additional approach: you can define functions inside other functions.

def processFile(filename: String, width: Int) = {
  def processLine(filename: String, width: Int, line: String) = {
    if (line.length > width)
      println(filename + ": " + line.trim)
  val source = Source.fromFile(filename)
  for (line <- source.getLines()) {
    processLine(filename, width, line)

Now that processLine is defined inside processFile, however, an- other improvement becomes possible. Notice how filename and width are passed unchanged into the helper function? This is not necessary because local functions can access the parameters of their enclosing function. You can just use the parameters of the outer processLine function:

object LongLines {
  def processFile(filename: String, width: Int) = {
    def processLine(line: String) = {
      if (line.length > width)
        println(filename + ": " + line.trim)
    val source = Source.fromFile(filename)
    for (line <- source.getLines())

LongLines with a local processLine function

First-class functions

Scala has first-class functions. Not only can you define functions and call them, but you can write down functions as unnamed literals and then pass them around as values.

A function literal is compiled into a class that when instantiated at run-time is a function value.

Here is a simple example of a function literal that adds one to a number:

(x: Int) => x + 1
  • The => designates that this function converts the thing on the left (any integer x) to the thing on the right (x + 1).
  • So, this is a function mapping any integer x to x+1.

Function values are objects, so you can store them in variables if you like. They are functions, too, so you can invoke them using the usual parentheses function-call notation. Here is an example of both activities:

var increase = (x: Int) => x + 1

If you want to have more than one statement in the function literal, surround its body by curly braces and put one statement per line, thus forming a block.

increase = (x: Int) => {
   x + 1

Many Scala libraries give you opportunities to use them. For example, a foreach method is available for all collections. It takes a function as an argument and invokes that function on each of its elements. Here is how it can be used to print out all of the elements of a list:

val someNumbers = List(-11, -10, -5, 0, 5, 10)
someNumbers.foreach((x: Int) => println(x))

As another example, collection types also have a filter method. This method selects those elements of a collection that pass a test the user supplies. That test is supplied using a function.

someNumbers.filter((x: Int) => x > 0)

Short forms of function literals

Scala provides a number of ways to leave out redundant information and write function literals more briefly. Keep your eyes open for these opportunities, because they allow you to remove clutter from your code.

One way to make a function literal more brief is to leave off the parameter types. Thus, the previous example with filter could be written like this:

someNumbers.filter((x) => x > 0)

The Scala compiler knows that x must be an integer, because it sees that you are immediately using the function to filter a list of integers (referred to by someNumbers). This is called target typing because the targeted usage of an expression (in this case, an argument to someNumbers.filter()) is allowed to influence the typing of that expression (in this case to determine the type of the x parameter).

You can simply start by writing a function literal without the argument type, and if the compiler gets confused, add in the type. Over time you’ll get a feel for which situations the compiler can and cannot puzzle out.

A second way to remove useless characters is to leave out parentheses around a parameter whose type is inferred. In the previous example, the parentheses around x are unnecessary:

someNumbers.filter(x => x > 0)

Placeholder syntax

To make a function literal even more concise, you can use underscores as placeholders for one or more parameters, so long as each parameter appears only one time within the function literal.

someNumbers.filter(_ > 0)

Sometimes when you use underscores as placeholders for parameters, the compiler might not have enough information to infer missing parameter types. In such cases, you can specify the types using a colon, like this:

val f = (_: Int) + (_: Int)
f(5, 10)

Note that _ + _ expands into a literal for a function that takes two parameters. This is why you can use this short form only if each parameter appears in the function literal exactly once. Multiple underscores mean multiple pa- rameters, not reuse of a single parameter repeatedly.

Partially applied functions

Although the previous examples substitute underscores in place of individual parameters, you can also replace an entire parameter list with an underscore. For example, rather than writing println(_), you could write println _. Here’s an example:

someNumbers.foreach(println _)

Scala treats this short form exactly as if you had written the following:

someNumbers.foreach(x => println(x))

Thus, the underscore in this case is not a placeholder for a single parameter. It is a placeholder for an entire parameter list.

When you use an underscore in this way, you are writing a partially applied function. In Scala, when you invoke a function, passing in any needed arguments, you apply that function to the arguments. For example, given the following function:

def sum(a: Int, b: Int, c: Int) = a + b + c

A partially applied function is an expression in which you don’t supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments. For example, to create a partially applied function expression involving sum, in which you supply none of the three required arguments, you just place an underscore after “sum”. The resulting function
can then be stored in a variable. Here’s an example:

val a = sum _
a: (Int, Int, Int) => Int = <function 3>

a(1, 2, 4)
res11: Int = 6

The class generated by the compiler has an apply method that takes three arguments. The generated class’s apply method takes three arguments because three is the number of arguments missing in the sum _ expression.

Thus, a(1, 2, 3) is a short form for:

a.apply(1, 2, 3)

This apply method, defined in the class generated automatically by the Scala compiler from the expression sum _.

Another way to think about this kind of expression, in which an underscore is used to represent an entire parameter list, is as a way to transform a def into a function value.

val b = sum(1, _: Int, 3)
b: Int => Int = <function1>

In this case, you’ve supplied the first and last argument to sum, but not the middle argument. Since only one argument is missing, the Scala compiler generates a new function class whose apply method takes one argument.

Int = 6

If you are writing a partially applied function expression in which you leave off all parameters, such as println _ or sum _, you can express it more concisely by leaving off the underscore if a function is required at that point in the code.

If you are writing a partially applied function expression in which you
leave off all parameters, such as println _ or sum _, you can express it more concisely by leaving off the underscore if a function is required at that point in the code.

For example, you could just write:



  • A function literal with no free variables, such as (x: Int) => x + 1, is called a closed term.
  • Any function literal with free variables, such as (x: Int) => x + more, is an open term.

Therefore, any function value created at runtime from (x: Int) => x + more will, by definition, require that a binding for its free variable, more, be captured.

This example brings up a question: What happens if more changes af- ter the closure is created? In Scala, the answer is that the closure sees the change. For example:

more = 9999

Int = 10009

Intuitively, Scala’s closures capture variables themselves, not the value to whichvariablesrefer.

By contrast, Java’s inner classes do not allow you to access modifiable variables in surrounding scopes at all, so there is no difference between capturing a variable and capturing its currently held value.

Only one answer is consistent with the rest of the language: the instance used is the one that was active at the time the closure was created. For example, here is a function that creates and returns “increase” closures:

def makeIncreaser(more: Int) = (x: Int) => x + more

Each time this function is called it will create a new closure. Each closure
will access the more variable that was active when the closure was created.

It makes no difference that the more in this case is a parameter to a method call that has already returned. The Scala compiler rearranges things in cases like these so that the captured parameter lives out on the heap, instead of the stack, and thus can outlive the method call that created it. This rearrangement is all taken care of automatically, so you don’t have to worry about it. Capture any variable you like: val, var, or parameter.

Special function call forms

Repeated parameters

Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. To denote a repeated parameter, place an asterisk after the type of the parameter.

def echo(args: String*) = for (arg <- args) println(arg)

Defined this way, echo can be called with zero to many String arguments.

If you have an array of the appropriate type, and you attempt to pass it as a repeated parameter, you’ll get a compiler error:

val arr = Array("What's", "up", "doc?")

<console>:10: error: type mismatch;
found   : Array[String]
required: String

To accomplish this, you’ll need to append the array argument with a colon and an _* symbol, like this:

echo(arr: _*)

This notation tells the compiler to pass each element of arr as its own argument to echo, rather than all of it as a single argument.

Named arguments

Named arguments allow you to pass arguments to a function in a differ- ent order. The syntax is simply that each argument is preceded by a param- eter name and an equals sign.

def speed(distance: Float, time: Float): Float = distance /time
speed(100, 10)
speed(time = 10, distance = 100)

Default parameter values

Default parameters are especially helpful when used in combination with named parameters. Function printTime2 has two optional parameters. The out parameter has a default of Console.out, and the divisor parameter has a default value of 1.

def printTime2(out: = Console.out, divisor: Int = 1) =
  out.println("time = " + System.currentTimeMillis() / divisor)

A function with two parameters that have defaults

Tail recursion

def approximate(guess: Double): Double =
  if (isGoodEnough(guess)) guess
  else approximate(improve(guess))

Tail recursive

def approximateLoop(initialGuess: Double): Double = {
  var guess = initialGuess
  while (!isGoodEnough(guess)) guess = improve(guess)

While loop

  • This might seem surprising because a recursive call looks much more “expansive” than a simple jump from the end of a loop to its beginning.
  • However, in the case of approximate above, the Scala compiler is able to apply an important optimization. Note that the recursive call is the last thing that happens in the evaluation of function approximate’s body.
  • Functions like approximate, which call themselves as their last action, are called tail recursive. The Scala compiler detects tail recursion and replaces it with a jump back to the beginning of the function, after updating the function parameters with the new values.
  • The moral is that you should not shy away from using recursive algorithms to solve your problem. Often, a recursive solution is more elegant and concise than a loop-based one. If the solution is tail recursive, there won’t be any runtime overhead to be paid.

Tracing tail-recursive functions

def boom(x: Int): Int =
  if (x == 0) throw new Exception("boom!")
  else boom(x - 1) + 1

This function is not tail recursive, because it performs an increment operation after the recursive call.

If you think you might be confused by tail-call optimizations when looking at a stack trace, you can turn them off by giving the following argument to the scala shell or to the scalac compiler:


Limits of tail recursion

If the recursion is indirect, as in the following example of two mutually recursive functions, no optimization is possible:

def isEven(x: Int): Boolean =
  if (x == 0) true else isOdd(x - 1)
def isOdd(x: Int): Boolean =
  if (x == 0) false else isEven(x - 1)

You also won’t get a tail-call optimization if the final call goes to a function value.


Scala provides local functions, function literals, and function values. In addition to normal function calls, Scala provides partially applied functions and functions with repeated parameters. When possible, function calls are implemented as optimized tail calls, and thus many nice-looking recursive functions run just as quickly as hand-optimized versions that use while loops.