Oracle unveiled the first implementation of Java 7 official closures and lambda expressions a few days ago, which is essentially the style of the final version in the official edition. After seeing this realization, my first feeling is "ugly", of course, I do not rule out this because I am accustomed to the implementation of other languages. After a closer look and thought, the realization of Java 7 is not without its merits, but there seems to be some problems with some practices. In short, the whole process was interesting, and decided to write down my thoughts, hoping to attract people to discuss it.
Lambda Expressions in Java 7
There are two forms of lambda expressions in Java 7, first of all:
#int() func1 = #()(3); // "func1.()" returns 3
#int(int) func2 = #(int x)(x + 1); // "func2.(3)" returns 4
#int(int, int) func3 = #(int x, int y)(x - y); // "func3.(5, 3)" returns 2
Then there is the second, which is equivalent to the above:
#int() func1 = #(){ return 3; };
#int(int) func2 = #(int x){ return x + 1; };
#int(int, int) func3 = #(int x, int y){ return x – y; };
If the body of the lambda is a "single expression", you can use parentheses and omit the last return keyword, and if you need to include more than one statement in the body, you must use curly braces, and curly braces can contain multiple statements, like a normal method. These two types of writing also have corresponding objects in C #, as in "single expression":
// C#
Func<int> func1 = () => 3; // "func1()" returns 3
Func<int, int> func2 = x => x + 1; // "func2(3)" returns 4
Func<int, int, int> func3 = (x, y) => x - y; // "func3(5, 3)" returns 2
The second type, which is more than one statement:
// C#
Func<int> func1 = () => { return 3; };
Func<int, int> func2 = x => { return x + 1; };
Func<int, int, int> func3 = (x, y) => { return x – y; };
Both Java and C # 's lambda expressions consist of two parts: argument list and expression body, but they differ as follows:
There are no delimiters between the argument list and the expression body in Java, and C # is delimited with "=>".
For a lambda for a single expression, C # can not use parentheses to contain an expression body, and Java must use parentheses.
If there is only a single parameter, then C # 's argument list can omit parentheses, and Java must retain it.
C # makes "type inference" for the argument list, and Java must write out the parameter types.