Hi all,

       Lambda expression for Groovy has been completed with a little
limitation, which is due to the existing closure whose parameter list can be
ambiguous to lambda expression, e.g. {a -> a} which can be parsed as a
lambda expression in a block, but we expect it a closure. In order to
resolve the ambiguities, the parentheses for parameters is a must, e.g.
*Java8* allows parentheses-less parameter for lambda when the parameter is
single and without type: e -> e, but *Groovy* only allows parameter with
parentheses: (e) -> e.

       *Here are some examples for lambda expression for Groovy:*
assert 9 == [1, 2, 3].stream().map((e) -> e + 1).reduce(0, (r, e) -> r + e)
assert 9 == [1, 2, 3].stream().map((e) -> e + 1).reduce(0, (r, e) -> {r +
e})
assert 32 == ((e) -> e + 1)(2) + ((e, f) -> e + f)(2, 3) + ((e, f, g) -> e *
f * g)(2, 3, 4)
assert 24 == ((e, f, g) -> {e * f * g})(2, 3, 4)
assert 24 == ((int e, int f, int g) -> {
    int tmpE = e;
    int tmpF = f;
    int tmpG = g;
    return tmpE * tmpF * tmpG;
})(2, 3, 4)
assert 24 == ((int e, int f, int g=4) -> {
    int tmpE = e;
    int tmpF = f;
    int tmpG = g;
    return tmpE * tmpF * tmpG;
})(2, 3)
def list = [2, 3, 1]
Collections.sort(list, (n1, n2) -> n1 <=> n2)
assert [1, 2, 3] == list


       *BTW, lambda expression is the first-class citizen in the expression
hierarchy, you can use lambda expression in the almost any place where you
use the closure as usual.* More information can be found at the home of
groovy-parser: https://github.com/danielsun1106/groovy-parser/

        *In addition, you can try the groovy-parser by following the steps:*
$ git clone https://github.com/danielsun1106/groovy-parser.git
$ cd groovy-parser
$ ./gradlew groovyConsole


Cheers,
Daniel.Sun



--
View this message in context: 
http://groovy.329449.n5.nabble.com/Lambda-expression-for-Groovy-3-tp5736169.html
Sent from the Groovy Dev mailing list archive at Nabble.com.

Reply via email to