...

/

Anonymous Functions

Anonymous Functions

You will receive an introduction to anonymous functions in this lesson.

Anonymous functions: Definition

The code can be more readable and concise when short functions are defined without traditional function definitions.

Anonymous functions, which are also known as function literals or lambdas, allow us to define functions inside of expressions. Anonymous functions can be used at any point where a function pointer can be used.

We will get to their shorter => syntax later below. Let’s first see their full syntax, which is usually too wordy especially when it appears inside of other expressions:

function return_type(parameters) { 
    /* operations */ 
}

For example, an object of NumberHandler that produces 7 times the numbers that are greater than 2 can be constructed by anonymous functions as in the following code:

new NumberHandler(function bool(int number) { return number > 2; }, 
                  function int(int number) { return number * 7; });

Two advantages of the code above are that the functions are not defined as proper functions and their implementations are visible right where the NumberHandler object is constructed.

Note that the anonymous function syntax is very ...