Anonymous method #
An anonymous method is a method without a name.
Illustration #
We saw earlier that two mathematical functions may only differ by their names. This also holds for two methods:
int square(int x){
return x * x;
}
int toThePowerOfTwo(int x){
return x * x;
}
So in a sense, these two methods are the same method.
An anonymous method abstracts away from the name of the method. For instance, in Java, the two methods above could be described with the following lambda expression:
(int x) -> { return x * x; }
Or (with a more concise syntax):
x -> x * x
Warning. As we saw earlier, a common mathematical notation for this anonymous function is
$$ x \mapsto x^2 $$
So Java uses
->
for the mathematical symbol $\mapsto$, not for $\to$ (which is normally used for the type of a function).