Anonymous functions are functions that are defined but not assigned a name.
The following is an anonymous function that takes in two integers and returns the sum.
The resultant expression can be assigned to a val:
Anonymous functions are primarily used as arguments to other functions. For instance, the map function on a collection expects another function as its argument:
The types of the arguments of the anonymous function can be omitted: the types are inferred automatically:
If there is just one argument, the parentheses around that argument can be omitted:
There is an even shorter syntax that doesn't require names for the arguments. The above snippet can be written:
_ represents the anonymous function arguments positionally. With an anonymous function that has multiple parameters, each occurrence of _ will refer to a different argument. For instance, the two following expressions are equivalent:
When using this shorthand, any argument represented by the positional _ can only be referenced a single time and in the same order.