15 Anonymous Functions
After reading this lesson, you will be able to:
- Implement anonymous functions
- Code using the concise notation for anonymous functions
In lesson 6, you have learned the basics of functions in Scala. In this lesson, you’ll discover a new type of function called “anonymous”. Anonymous functions are functions that you can define quickly and concisely. At first, they may seem just an alternative to the standard Scala functions you have seen so far, but you’ll soon discover that they are particularly handy when combined with another type of function, called “higher order”. The concept of anonymous function is not unique to Scala: other languages, such as Java 8+, and Python, refer to it as “lambda”. In the capstone, you will use a particular kind of anonymous function called “partial” to define your HTTP server’s routes.
15.1 Function versus Anonymous Function
Suppose you have implemented a calculator program to perform the standard operations on integers (i.e., sum, subtraction, multiplication, division) together with negation. Listing 15.1 shows a possible implementation: