I have pasted some code from Jon Skeet's C# In Depth site:
static void Main() { // First build a list of actions List<Action> actions = new List<Action>(); for (int counter = 0; counter < 10; counter++) { actions.Add(() => Console.WriteLine(counter)); } // Then execute them foreach (Action action in actions) { action(); } }
http://csharpindepth.com/Articles/Chapter5/Closures.aspx
Notice the line:
actions.Add( ()
What does the () mean inside the brackets?
I have seen several examples of lambda expressions, delegates, the use of the Action object, etc but I have seen no explanation of this syntax. What does it do? Why is it needed?
In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side.
A lambda in Java essentially consists of three parts: a parenthesized set of parameters, an arrow, and then a body, which can either be a single expression or a block of Java code.
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
Java Lambda Expression Syntax Java lambda expression is consisted of three components. 1) Argument-list: It can be empty or non-empty as well. 2) Arrow-token: It is used to link arguments-list and body of expression. 3) Body: It contains expressions and statements for lambda expression.
This is shorthand for declaring a lambda expression which takes no arguments.
() => 42; // Takes no arguments returns 42 x => 42; // Takes 1 argument and returns 42 (x) => 42; // Identical to above
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With