15 使用lambdas和闭包

1       使用lambdas和闭包

1.1  定义闭包

闭包是一个代码块,代替了方法或类。

groovy中的闭包基于后边的构造方式:{list of parameters-> closure body}.其中,-> 之前的值为声明的闭包参数。

如果只有一个变量的时候,可以使用固有变量 it 。

如果没有返回值被定义,则返回-> 后边的值。it 的返回值的用法,参见下例子,

package closures

 

class ClosuresTest {

 

    static main(args) {

       //返回input,使用固有的变量it

       def returnInput = {it};

       assert "test" == returnInput("test");

       //返回input,不使用固有的变量it

       def returnInput2 = {s->s};

       assert "test" == returnInput2("test");

    }

 

}

1.2  闭包中定义默认值

闭包中,也可以定义参数的默认值。

package closures

 

class ClosuresDefaultValue {

 

    static main(args) {

       def multiply = {int a,int b=10 ->

           a*b;

       };

       assert multiply(2) == 20;

       assert multiply(2,5) == 10

    }

 

}

1.3  例子:each方法中使用闭包

在集合中使用闭包的例子,

package closures

 

class ClosuresEach {

 

    static main(args) {

       List<Integer> list = [5,6,7,8];

       println ("====自定义变量");

       list.each {line ->

           print line+",";

       };

       println (" ====固有变量");

       list.each ({

           print it+",";

       });

       println (" ====计算从1到10的和");

       def total = 0;

       (1..10).each {

           total += it;

       };

       println total;

    }

 

}

1.4  例子:通过string的长度对list排序

package closures

 

class ClosuresSort {

 

    static main(args) {

       def List strings = "this is a long sentence".split();

       strings.sort{s1,s2 ->

           s1.size() <=> s2.size();

       };

       println strings;

    }

 

}

输出

[a, is, this, long, sentence]

1.5  使用with方法

每个groovy对象都有一个with 方法,在该方法内,允许调用多个方法或属性,并将所设置的值或执行的方法都应用到该对象中。

package closures

 

import java.util.List;

 

class WithObj {

    String property1;

    String property2;

    List<String> list = [];

    def addElement(value) {

       list << value;

    };

    def returnProperties() {

       "Property 1:$property1,Property 2:$property2";

    }

}

package closures

 

class ClosuresWithMethod {

    static main(args) {

       def sample = new WithObj();

       def result = sample.with {

           property1="Input 1";

           property2="This is cool";

           addElement("Ubuntu");

           addElement("Android");

           addElement("Linux");

           returnProperties();

       };

       println result;

       assert 3==sample.list.size();

       assert "Input 1" == sample.property1;

       assert "This is cool" == sample.property2;

       assert "Linux" == sample.list[2];

      

       def sb = new StringBuilder();

       sb.with {

           append("this ");

           append("is ");

           append("appended");

       };

       println sb;

    }

 

}

输出:

Property 1:Input 1,Property 2:This is cool

this is appended

原文地址:https://www.cnblogs.com/yaoyuan2/p/5719192.html