9.1. Using Function Literals (Anonymous Functions)

Problem

You want to use an anonymous function—also known as a function literal—so you can pass it into a method that takes a function, or to assign it to a variable.

Solution

Given this List:

val x = List.range(1, 10)

you can pass an anonymous function to the List’s filter method to create a new List that contains only even numbers:

val evens = x.filter((i: Int) => i % 2 == 0)

The REPL demonstrates that this expression indeed yields a new List of even numbers:

scala> val evens = x.filter((i: Int) => i % 2 == 0)
evens: List[Int] = List(2, 4, 6, 8)

In this solution, the following code is a function literal (also known as an anonymous function):

(i: Int) => i % 2 == 0

Although that code works, it shows the most explicit form for defining a function literal. Thanks to several Scala shortcuts, the expression can be simplified to this:

val evens = x.filter(_ % 2 == 0)

In the REPL, you see that this returns the same result:

scala> val evens = x.filter(_ % 2 == 0)
evens: List[Int] = List(2, 4, 6, 8)

Discussion

In this example, the original function literal consists of the following code:

(i: Int) => i % 2 == 0

When examining this code, it helps to think of the => symbol as a transformer, because the expression transforms the parameter list on the left side of the symbol (an Int named i) into a new result using the algorithm on the right side of the symbol (in this case, an expression that results in a Boolean).

As mentioned, this example shows the long form ...

Get Scala Cookbook 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.