Home > Articles

This chapter is from the book

12.2 Anonymous Functions

In Scala, you don’t have to give a name to each function, just like you don’t have to give a name to each number. Here is an anonymous function:

(x: Double) => 3 * x

This function multiplies its argument by 3.

Of course, you can store this function in a variable:

val triple = (x: Double) => 3 * x

That’s just as if you had used a def:

def triple(x: Double) = 3 * x

But you don’t have to name the function. You can just pass it to another function:

Array(3.14, 1.42, 2.0).map((x: Double) => 3 * x)
  // Array(9.42, 4.26, 6.0)

Here, we tell the map method: “Multiply each element by 3.”

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.